Overridden global variable

I am a little confused by 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 is the result of 10 not 20?

+4
source share
5 answers

A call to afunc changes global g , and main retains its local g .

Entering a function does not replace a scope with a global scope. Each function * has its own area.

* Among other things

+5
source

The local variable g obscures the global g .

If you want printf() display 20, you must obscure your local variable g global declaration that 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; } 
+6
source

If you get rid of int in

 int g = 10; 

then main will also refer to the same global variable as afunc .

This is called changing variables.

+2
source

DO NOT change your code, but adjusted your comments to indicate what the code is doing. By the way, commenting on your code is a really good idea and makes for a better lab analysis! signed, former graduate student of TA

 #include <stdio.h> int g; /* define a global variable void afunc(int x) { g = x; /* this sets the global to whatever x is */ } int main(void) { int g = 10; /* Define and set a Local g to 10 */ afunc(20); /* This function sets global x to 20 */ printf("%d\n", g); /* this prints local g "10" */ return 0; } 

Think of this β€œsearch” from the main to global storage. You see local g in front of global g, so local g is used.

+1
source

In both cases, although the variable name seems to be the same, they 2 refer to 2 different memory areas. The variable g declared outside of any function was stored in the RAM area, and the variable g declared inside the main one was stored in the stack area. Thus, calling afunc () changes the variable g stored in RAM, but again prints the variable g (stored on the stack), which was declared locally.

0
source

Source: https://habr.com/ru/post/1495852/


All Articles