Why does overriding a static global variable give a compile-time error when overriding a global variable?

Compiling code 1 gives the error ' i redefined ', but code 2 does not show a similar error. Why is this so?

Code 1

 static int i; //Declaring the variable i. static int i=25; //Initializing the variable. static int i; //Again declaring the variable i. int main(){ return 0; } 

Code 2

 int i; //Declaring the variable i. int i=25; //Initializing the variable. int i; //Again declaring the variable i. int main(){ return 0; } 
+7
source share
1 answer

Both must compile.

Both int i; and static int i; are preliminary definitions in C because they have no initializer and are not extern . You are allowed several preliminary declarations and no more than one unintentional definition for any object in translation units, if the definitions do not conflict with the type or relationship.

ISO / IEC 9899: 1999 6.9.2:

Declaring an identifier for an object with a file area without an initializer and without a storage class specifier or static storage class specifier is a preliminary definition. If the translation unit contains one or more preliminary definitions for the identifier, and the translation unit does not contain external definitions for this identifier, then the behavior is performed exactly as if the translation unit contained the declaration of the scope of this identifier, and the composite type as the end of the translation block, moreover initializer is 0.

+10
source

All Articles