Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c - 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 
",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 
",a);
  return 0;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...