Anjaneyulu
Anjaneyulu

Reputation: 434

Why does this code not generate a redeclaration Error?

Here is an extern and a static variable with same name. The output prints the static variable a=10. Why is there no syntax error and how would I access extern a if needed?

#include<stdio.h>
extern int a;
static int a=10;

main()
{
    printf("%d\n",a);
}

Upvotes: 0

Views: 263

Answers (1)

AlexD
AlexD

Reputation: 32576

The C standard allows the opposite, extern after static:

6.2.2 Linkages of identifiers
....
3 If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

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. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

At the same time it states:

7 If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

BTW, the C++ standard makes it explicit:

7.1.1 Storage class specifiers
....

static int b; // b has internal linkage
extern int b; // b still has internal linkage

....

extern int d; // d has external linkage
static int d; // error: inconsistent linkage

Upvotes: 2

Related Questions