Declaring and assigning variables with file scope

2019-09-07 20:50发布

问题:

Say I declare the following variable:

int num;
num = 0;

int main(void)
{
        /* ... */
        exit(EXIT_SUCCESS);
}

The compiler will complain about num being undeclared and that it will default to type int. This does not happen when I do it all in one step:

int num = 0;

or if I move the assignment into main():

int main(void)
{
        num = 0;
        /* ... */
        exit(EXIT_SUCCESS);
}    

I once read an explanation for this behavior but I cannot find it anymore. Could someone update me again.

I'm compiling with

gcc -std=c11 -O2 -g -pedantic -Wall -c -fmessage-length=0 -v

回答1:

num = 0; is a statement that can exist only inside a function. It cannot exist in a global scope.

If you put a statement outside a function, it's wrong and not allowed. Simply think this like, if you have a statement outside all the functions, in a global scope, when and how that statement can be executed? So, that's wrong.

A special case, initialization while defining is allowed in a form of int num = 0;