假设以下最小代码:
#include <stdio.h>
char character = 'c';
int main (void)
{
char character = 'b';
printf("The current value of head is %c", character);
}
Run Code Online (Sandbox Code Playgroud)
我覆盖了character
内部main
,
然后发生了什么事c
?它会被自动销毁还是永久存在于记忆中?
这个评论点击了我:"C中的变量只不过是命名的内存块".
dbu*_*ush 13
您有两个单独的变量character
:一个在文件范围设置为'c',其生命周期是程序的生命周期,另一个main
设置为'b',其生命周期是其范围.
的定义character
在main
口罩在文件范围的定义,所以只有后者访问.
补充其他答案:
试试这个,你会明白:
#include <stdio.h>
char character = 'c';
void Check()
{
printf("Check: c = %c\n", character);
}
int main(void)
{
char character = 'b';
printf("The current value of head is %c\n", character);
Check();
}
Run Code Online (Sandbox Code Playgroud)
它会继续存在(直到程序死掉,就像任何静态存储变量一样),你仍然可以使用它:
#include <stdio.h>
char character = 'c';
int main (void)
{
char character = 'b';
printf("The current value of head is '%c'\n", character);
{
extern char character;
//in this scope, overrides the local `character` with
//the global (extern?) one
printf("The current value of head is '%c'\n", character);
}
printf("The current value of head is '%c'\n", character);
}
/*prints:
The current value of head is 'b'
The current value of head is 'c'
The current value of head is 'b'
*/
Run Code Online (Sandbox Code Playgroud)
对于static
全局变量,本地extern声明不能可靠/可移植地工作,尽管你仍然可以通过指针或通过单独的函数来获取它们.
(为什么static char character='c'; int main(){ char character='b'; { extern char character; } }
全球存在不可靠static
?
6.2.2p4似乎也想让它对静力学起作用,但是措辞含糊不清(先前的声明没有联系,另一个有静态/外部联系所以现在呢?).
对于在范围内使用存储类说明符extern声明的标识符,其中该标识符的先前声明是可见的,31)如果先前声明指定内部或外部链接,则后面声明中标识符的链接与在先前声明中指定的联系.如果没有先前声明可见,或者先前声明未指定链接,则标识符具有外部链接.
我的clang 6.0.0接受它static char character='b';
但是我的gcc 7.3.0不是.
感谢Eric Postpischil指出了这种可行性的模糊可能性static
.)