当没有参考价值时,价值是否会永久存在?

Alg*_*bra 13 c

假设以下最小代码:

#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中的变量只不过是命名的内存块".

Mys*_*yst 24

" 遮蔽 "全局character变量隐藏了main函数中的变量,但它仍然是程序的一部分.

如果character变量被声明为static,则编译器可能会警告该character变量从未被使用过并且character将被优化掉.

但是,character变量未声明为static; 编译器将假定character可以从外部访问character变量并在内存中保持变量.

编辑:

如@Deduplicator所述,如果允许,链接器优化和设置可以省略最终可执行文件中的变量.但是,这是一个不会"自动"发生的边缘情况.


dbu*_*ush 13

您有两个单独的变量character:一个在文件范围设置为'c',其生命周期是程序的生命周期,另一个main设置为'b',其生命周期是其范围.

的定义charactermain 口罩在文件范围的定义,所以只有后者访问.


Jab*_*cky 6

补充其他答案:

试试这个,你会明白:

#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)


PSk*_*cik 5

它会继续存在(直到程序死掉,就像任何静态存储变量一样),你仍然可以使用它:

#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似乎也想让它对静力学起作用,但是措辞含糊不清(先前的声明没有联系,另一个有静态/外部联系所以现在呢?).

6.2.2p4:

对于在范围内使用存储类说明符extern声明的标识符,其中该标识符的先前声明是可见的,31)如果先前声明指定内部或外部链接,则后面声明中标识符的链接与在先前声明中指定的联系.如果没有先前声明可见,或者先前声明未指定链接,则标识符具有外部链接.

我的clang 6.0.0接受它static char character='b';但是我的gcc 7.3.0不是.

感谢Eric Postpischil指出了这种可行性的模糊可能性static.)