Pergunta

    #include <stdio.h>

    int i;

    int main()

    {

        extern int i;

        if (i == 0)

            printf("scope rules\n");

    }

Output: scope rules

How extern variable works here?

Why there is no error like Compile time error due to multiple declaration

Foi útil?

Solução

extern doesn't actually create the variable though. It is like the forward declaration of a class, or the prototype of a function. Variable "i" at the starting creates a global integer named "i" which will exist in the current compilation unit, whereas "i" under the "int main" is a declaration that an integer named "i" exists somewhere in some compilation unit, and any uses of the name "i" refer to that variable.

Outras dicas

Because you can declare that something exists as many times as you want to (provided the type is the same each time), but you can only define it once.

extern int i is a declaration that i exists, and is an int.

Where it exists is at the file level (the int i after the headers), with static storage duration. That means it's initialised to zero so you will always see the output "scope rules".

It's a subtle concept, the declaration/definition distinction, but it's one every C programmer should eventually learn well.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top