+ 1

Help me explain the code and how the output come up. Thank you

Please help me explain a C languange source code https://code.sololearn.com/cFOr5FrXsA0H/?ref=app

21st Nov 2022, 9:33 AM
clavel skie
clavel skie - avatar
3 odpowiedzi
+ 4
a=1; b=2; c=3; trace(&a,&b,c); this is calling function trace with passing addresses of a,b and passing value of c. in the function x stores a address ( *x = &a ), and y stores b address. z stores c value so then *x = 1, *y = 2 , z = 3 int t; // creates new variable t of type int z+= *x; // z = z + *x => 3+1= 4 => z = 4; *x= *y+z; // *x = 2+4 = 6 => *x = 6 t=z; // t = z => t = 4 z=*y; => z = *y => z = 2 *y=*x; => *y = 6 *x=t; => *x = 4 so finally *x = 4, *y = 6, z = 2 =>in back to main => a=4,b=6,c=3 printf("%d %d %d\n", a, b, c); // 4,6,3 // this works same , on returns calculation of trace(&a, &b, c); // You can trace now *x = 4, *y = 6 , z = 3 int t; // creates new variable t of type int z+= *x; // z = z + *x => 3+4= 7 => z = 7; *x= *y+z; // *x = 6+7 = 13 => *x = 13 t=z; // t = z => t = 7 z=*y; => z = *y => z = 6 *y=*x; => *y = 13 *x=t; => *x = 7 so finally *x = 7, *y = 13, z = 6 =>in back to main => a=7,b=13,c=3 printf("%d %d %d\n", a, b, c); // printing values..
21st Nov 2022, 11:02 AM
Jayakrishna 🇮🇳
+ 3
Where is your doubt? Can you add your understandings..!? trace(a, b, c) ; are just passing values. It is pass by values. Changes in the values of parameters in the function don't reflect back on original passed parameters. trace( &a, &b, c) ; here &a returns the address of variable a so passing variable address instead of value and storing it in a pointer *x in function so changes in *x will reflect back on variable a . It is pass by reference method. Look at first 2 calls : trace(&a, &b, c) ; // changes reflect on a, b but not on c. 3rd call : trace( &c, &b, a) ; changes in c, b in function will reflect back but not on a. if anything not understood then mention that specifics.... hope it helps...
21st Nov 2022, 10:31 AM
Jayakrishna 🇮🇳
+ 1
I'm only a beginner so I don't fully understand the code like the first function has the output of 4 6 3 and I don't understant how it became like that. Can you please eleborate your explanation. Thank you
21st Nov 2022, 10:37 AM
clavel skie
clavel skie - avatar