Search code examples
cdeclarationdefinitionredefinitionone-definition-rule

Redeclaration of global variable vs local variable


When I compile the code below

#include<stdio.h>

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

I get an error:

test3.c: In function ‘main’:
test3.c:6:5: error: redeclaration of ‘a’ with no linkage
test3.c:5:5: note: previous declaration of ‘a’ was here

But if I make the variable global then it works fine.

#include<stdio.h>

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

Why is declaring the same global variable twice not an error, but doing that for a local variable is an error?


Solution

  • 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.