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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -