Scope of a variable outside main in C

前端 未结 7 594
深忆病人
深忆病人 2020-12-15 21:41

Consider the code:

#include 

int x;

int main (void) 
{ }

The value of x is 0 inside main

7条回答
  •  离开以前
    2020-12-15 22:31

    x is a global variable, it has space allocated for it when the program starts and is initialized to 0 (generally, however you should have an explicit initializer).

    The 'static' keyword has two different meanings.

    1)

    static int x;
    
    int main() { }
    

    This limits the scope of x to the single file. Although it is still a global variable, the linker will not be able to connect references to x from other files.

    2)

    int main() {
       static int x;
    }
    

    This effectively turns x into a global variable. Although the scope is still within the main function, space is allocated for it globally, and it's value will be retained between calls to main().

提交回复
热议问题