Scope of a variable outside main in C

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

Consider the code:

#include 

int x;

int main (void) 
{ }

The value of x is 0 inside main

7条回答
  •  Happy的楠姐
    2020-12-15 22:22

    6.2.2/5: "If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external."

    That's linkage, though, not scope. Your declaration of x would have file scope either way. static and extern don't affect scope. It's initialized to 0 because x has static storage duration (see 6.2.4/3 and /5).

    In general you also have to be aware of 6.2.2./4:

    For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration.

    So declaring with extern is not quite the same as declaring with no storage-class specifier. In your example there is no prior declaration, though.

提交回复
热议问题