#include <stdio.h>
int f1(int *x, int y) {
y ;
(*x) ;
return *x y;
}
int main() {
int x = 10, y = 5;
int z = f1(&x, y);
printf("x=%d y=%d z=%d\n", x, y, z);
}
I get the answer as x=11 y=5 z=17
.
Can someone explain this?
CodePudding user response:
Check the comments.
#include <stdio.h>
int f1(int *x,int y)
{
y ; // incrementing y, which was 5, to 6.
(*x) ; // incrementing the value-at-address-x, which was 10, to 11
return *x y; // add value-at-address-x, 11, and value of y, 6 == 17, return that.
}
int main(void) //correct signature of main in hosted environment
{
int x=10,y=5;
int z=f1(&x,y);
//any changes made to the value stored at address x will reflect here,
// any changes made to the value of y will be local to the function call.
printf("x=%d y=%d z=%d\n",x,y,z);
// updated x, unchanged y, and returned z.
}
CodePudding user response:
The formal arguments x
and y
in f1
are different objects in memory from the variables x
and y
in main
.
When you call z=f1(&x, y);
, the expressions &x
and y
are fully evaluated and the results of those expressions are copied to the formal parameters x
and y
(this is what we mean when we say C passes function arguments by value).
So the formal parameter x
stores the address of the variable x
and the formal parameter y
stores the value 5
.
Since the formal parameter y
is a different object in memory from the variable y
, changing its value has no effect on the y
in main
.
The expression *x
is f1
acts as kinda-sorta an alias for the variable x
, so changing the value of *x
in f1
does change the value of x
in main
.