Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

Compiling code 1 gives an error 'i 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;
}
like image 772
Suri Avatar asked Aug 27 '11 16:08

Suri


1 Answers

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.

like image 200
CB Bailey Avatar answered Oct 22 '22 17:10

CB Bailey