简体   繁体   中英

where and when do the global static and local static get stored and initialized?

include

static int i = 10;

int
main()
{
   static int i = 20;

   printf ( "i = %d\n", i );

   return 0;
}

There are two static variables, one in global scope and one in function scope. The compiler is not throwing "multiple definition" error. Could you please let me know where the two static vars are stored?

The two variables are stored separately because they are distinct - it is the compiler's problem to ensure that they are separate.

The variables are both initialized before the program starts - this is C, not C++, where the rules are slightly different.

Inside main() as shown, you cannot access the global variable i (again, this is C, not C++).

GCC's -Wshadow compiler flag would warn you about the local i shadowing the global one.

These variables are called "symbols", and during compiling a table is generated, the "symbol table". This table contains the name, type, scope and memory pointer to each symbol (this is like the minimum, you usually have a bunch of more stuff), and each time a reference is made to an symbol in a specific scope, it's substituted for an index into the table. These indices are unique, so is the combination of name+scope.

So in short, the names of the variables are simply decoration, internally the compiler works with a symbol table and indices into it. Statics are initialized during program startup by iterating through a table of pointers to them and putting the correct values in place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM