Rachana Pal
Rachana Pal

Reputation: 87

regarding the use of extern keyword

extern int var;

I understand that when we use extern keyword with a variable as shown below, memory for that variable is not allocated. (It is just a declaration)

extern int i = 0;

And I know that if we declare an extern variable and also provide an initializer along with that declaration, then the memory is allocated for that variable.

Also the below program is printing 0

#include <stdio.h>
int i; // Can I treat this as declaration/definition?
int main()
{
    printf("%d ", i);
    return 0;
}

I feel, here the variable i is being assigned the value 0.

If (int i; as shown above) is definition, why below code is not giving multiple definition ERROR?

#include <stdio.h>
int i;
int i;
int i;
int main()
{
    printf("%d ", i);
    return 0;
}

Upvotes: 3

Views: 87

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Without an explicit initialization, all the int is in global space are called tentative definition. However, this is not allowed in local scope.

To quote the C11 standard, chapter §6.9.2, External object definitions

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the 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 definition 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.

Upvotes: 4

Related Questions