Compiling code 1 gives an error 'i 开发者_StackOverflow社区redefined
', but code 2 shows no similar error. Why is it 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;
}
Both should compile.
Both int i;
and static int i;
are tentative definitions in C as they do not have an initializer and are not extern
. You are allowed multiple tentative declarations and at most one non-tentative definition for any object in a translation unit so long as the definitions don't conflict in type or linkage.
ISO/IEC 9899:1999 6.9.2:
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with a storage-class specifier
static
, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definitions for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
精彩评论