{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d",i);
}
}
我有两个问题
- 为什么
i
没有重新声明错误? - 为什么输出是
10
5 次而不是10
1 次?
最佳答案
这一切都与标识符的范围有关。标识符只是 C 中赋予实体(对象、函数、typedef 名称等)的名称,根据 C11 6.2.1/1
:
The same identifier can denote different entities at different points in the program.
实体的范围在该部分的 /2
中描述:
For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope.
并且 /4
涵盖您的具体情况:
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).
换句话说,类似于:
{
int i = 42;
printf ("%d ", i);
{
int i = 17;
printf ("%d ", i);
}
printf ("%d\n", i);
}
完全有效,并且将打印 42 17 42
。这是因为内部 block 内的标识符 i
位于其自己的范围内,该范围以第一个右大括号结束。
在您的特定情况下,您可以将其视为:
{
int i; \
for(i=0;i<5;i++) > outer i scope
{ /
int i=10; \
printf("%d",i); > inner i scope
} /
}
内部int i=10
有效地在for
循环体的持续时间内隐藏外部i
。这就是为什么它打印大量 10
而不是 0..4
。
内部i
的作用域在for
循环体的右大括号处结束,因此,当for
的继续条件满足时检查循环后,它再次看到外部的i
。这就是为什么它循环五次而不是一次。
关于c - 为什么在循环外部和内部声明具有相同名称的变量不会产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208481/