每个变量都引用其最近的声明(当然在该范围内有效):
main()
{
int i=3;
while(i--) // this i is the one defined in the line above
{
int i=100;
i--; // this i is the one defined in the line above
printf("%d..",i); // this i is the one defined two lines above
}
}
因此,您的 while 循环迭代 3 次,因为它取决于在它打印的循环内部i
声明的 that,因为 there引用了由ed声明的 that。int i = 3;
99
i
i
int i = 100;
--
如果您更改int i = 100;
为i = 100
,那么您将更改第i
一个变量,而不是引入另一个变量。因此无限循环。
编辑有些人说,而不是“最近的”,我应该说“在当前范围内可访问的最里面的声明”给出这个例子:
int a=4;
{
int a=10;
}
printf("%d", a);
由于第二个a
不可见printf
,显然printf("%d", a);
无法引用它。我假设读者知道的足够多,知道一个变量只能在它定义的范围内访问。否则,是的,前两条评论中的短语更准确。