Issue with scope of variables in C, why a function prints what it's supposed to print -
what going on in program here? why myfunction print 3 x?
int myfunction(int); void main(void) /* local variables: x, result in main */ { int result, x = 2; result = myfunction(x); printf("%i", result); /* prints "3" */ printf("%i", x); /* prints "2" */ } int myfunction (int x) { x = x + 1; printf("%i\n", x); /* prints "3" */ return x; }
that's because parameter local variable in function.
when function called, there space allocated on stack parameter, , value variable x
copied parameter.
in function parameter x
local varible, separate variable x
in calling code. when x
increased in function, happens local copy.
when function ends, parameter goes away when stack frame function removed stack.
Comments
Post a Comment