问题描述
当我编译如下
#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?
推荐答案
在C,语句 int类型的;
时,在文件范围内制成,是一个声明和一个暂定定义的。你可以有很多的暂定定义,只要你想,只要他们都相互匹配。
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.
这篇关于全局变量VS局部变量的重新声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!