I'm a little Confused about this code result:
#include <stdio.h>
int g;
void afunc(int x)
{
g = x; /* this sets the global to whatever x is */
}
int main(void)
{
int g = 10; /* Local g is now 10 */
afunc(20); /* but this function will set it to 20 */
printf("%d\n", g); /* so this will print "20" */
return 0;
}
Why the result is 10 Not 20 ?
The local variable g
shadows the global g
.
If you want the printf()
to show 20, you have to shadow your local variable g
with a declaration of the global one you want to print:
int main(void)
{
int g = 10; /* Local g is now 10 */
afunc(20); /* Set global g to 20 */
printf("%d\n", g); /* Print local g, "10" */
{
extern int g; /* Use global g */
printf("%d\n", g); /* Print global g, "20" */
}
return 0;
}
Calling afunc
changes the global g
, and main
retains its local g
.
Entering a function doesn’t swap its scope with the global scope. Each function* has its own scope.
* Among other things
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With