为什么不允许全局变量重新定义? [英] Why Global variable redefinition is not allowed?
问题描述
#include<stdio.h>
int i =0;
i=2;
int main(){
// some Code here
return 0;
}
错误: /Users/vaibhavkumar/Documents/C/primeFactors.c | 4 |错误:重新定义了"i" |
- 为什么在C中不允许重新定义变量.
- 全局变量存储在数据段(内存区域)中,与存储静态变量的位置相同.如何重新声明静态变量?
推荐答案
不是重新定义,而是赋值.
赋值与C中的初始化不同,并且不能在函数外部完成-在这种情况下没有执行线程,那么何时才能完成?
Assignment is not the same as initialisation in C, and cannot be done outside a function - there is no thread of execution in that context, so when would it be done?
具有 static
链接的变量在这方面与全局变量(具有 extern
链接)没有区别,但是静态链接变量是 local 单个编译单元,在外部不可见.如果在单独的编译单元中声明两个具有相同名称的静态变量,则它们完全是独立且不相关的变量-它们甚至不必是同一类型.
Variables with static
linkage are no different to global variables (with extern
linkage) in this respect, however static linkage variables are local to a single compilation unit and are not visible externally. If you declare two statics of the same name in separate compilation units, they are entirely independent and unrelated variables - they needn't even be the same type.
请注意,静态链接与静态存储不同,但是它们使用相同的关键字.所有全局和静态链接变量都隐式具有静态存储类,但是声明为static的 function local 变量具有 static存储类-即它始终存在-像全局一样,但仅本地可见.
Note that static linkage is distinct from static storage, but they use the same keyword. All global and static linkage variables have static storage class implicitly, but a function local variable declared static has static storage class - i.e. it always exists - like a global, but is only visible locally.
这篇关于为什么不允许全局变量重新定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!