Redeclaration of global variable vs local variable

后端 未结 3 1283
太阳男子
太阳男子 2020-11-30 07:17

When I compile the code below

#include

int main()
{
  int a;
  int a = 10;
  printf(\"a is %d \\n\",a);
  return 0;
}

I get

3条回答
  •  时光说笑
    2020-11-30 07:27

    In C, the statement int a; when made at file scope, is a declaration and a tentative definition. You can have as many tentative definitions as you want, as long as they all match each other.

    If a definition (with an initializer) appears before the end of the translation unit, the variable will be initialized to that value. Having multiple initialization values is a compiler error.

    If the end of the translation unit is reached, and no non-tentative definition was found, the variable will be zero initialized.

    The above does not apply for local variables. Here a declaration also serves as a definition, and having more than one leads to an error.

提交回复
热议问题