About using the extern keyword

extern int var;

      

My understanding is that when we use the keyword extern

with a variable as shown below, no memory is allocated for that variable. (This is just an announcement)

extern int i = 0;

      

And I know that if we declare a variable extern

and also provide an initializer along with that declaration, then memory will be allocated for that variable.

Also the below program prints 0

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

      

I feel like the variable is being i

assigned here 0

.

If ( int i;

as shown above) this is the definition, why doesn't the code below give a multiple definition of ERROR?

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

      

+3


source to share


1 answer


Without explicit initialization, everything int i

in the global space is called a pre-definition. However, this is not permitted in the local area.

To cite the standard C11

, section Β§6.9.2, external object definitions



Declaring an identifier for a file-scoped object without an initializer and without a storage class specifier, or with a static member of a storage class, is a provisional definition. If the translation unit contains one or more pre-defined definitions for an identifier, and the translation unit does not contain an external definition for that identifier, then the behavior is exactly the same as if the translation unit contained the scope declaration of this identifier with a composite type at the end of the translation block with the initializer. equal to 0.

+4


source







All Articles