gpt4 book ai didi

c - C 编程中的作用域(全局和局部变量)

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:17 25 4
gpt4 key购买 nike

#include <stdio.h>

int main () {
int i = 3;
printf("%d\n", i);
if (i == 3) {
i = i + 1;
int i = 6;
printf("%d\n", i);
i = i + 1;
}

if (i == 3) {
printf("%d\n", i);
}
return 0;
}

我的问题是为什么 4 和 7 消失了?

当我运行代码时,它们只打印输出 3 和 6?

最佳答案

这里没有任何东西“消失”,这是因为对于具有重叠范围的标识符,内部范围优先于外部范围。

引用 C11,第 6.2.1 章(强调我的)

[...] If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

所以,在你的情况下,(关注评论)

#include <stdio.h>

int main (void) { //note the correct signature
int i = 3; //outer scope of i
printf("%d\n", i);
if (i == 3) {
i = i + 1; //this happens in "outer" scope, i value changed...
//---------------------> |-----inner scope starts, outer scope gets hidden
int i = 6; // |
printf("%d\n", i); // |
i = i + 1; // |
}//------------------------> |-----inner scope ends, outer scope resumes

if (i == 3) { // hey. look , other scope is back!!!
printf("%d\n", i);
}
return 0;
}

关于c - C 编程中的作用域(全局和局部变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43890577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com