我正在阅读《 C Primer Plus》这本书,并且遇到了如下代码片段:
int main()
{
int x = 30;
printf("x in outer block: %d at %p\n", x, &x);
{
int x = 77; // new x , hides first x
printf("x in inner block: %d at %p\n", x, &x);
}
printf("x in outer block: %d at %p\n", x, &x);
while (x++ < 33) //original x
{
int x = 100;
x++;
printf("x in while loop: %d at %p\n", x, &x);
}
printf("x in outer block: %d at %p\n", x, &x);
return 0;
}
它输出:
In [23]: !./a.out
x in outer block: 30 at 0x7ffee7243788
x in inner block: 77 at 0x7ffee7243784
x in outer block: 30 at 0x7ffee7243788
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in outer block: 34 at 0x7ffee7243788
这让我很困惑
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
我如何使其输出?
x in while loop: 101 at 0x7ffee7243780
x in while loop: 102 at 0x7ffee7243780
x in while loop: 103 at 0x7ffee7243780
答案 0 :(得分:3)
之所以会这样,是因为在while
循环范围内,每次执行将变量x
重新定义为等于100,这遮盖了在外部定义的x
,因此您不必递增一三遍,但内心一遍。在每个新迭代中, new x都增加1,在输出中看到101。
答案 1 :(得分:2)
每次进入while循环时,将内部x值重置为100,就可以添加一个外部var,然后在while循环中将其递增,将其值添加到100。
int main()
{
int x = 30;
int y = 0;
printf("x in outer block: %d at \n", x);
{
int x = 77; /* new x , hides first x*/
printf("x in inner block: %d at \n", x);
}
printf("x in outer block: %d at\n", x);
while (x++ < 33) /*original x*/
{
int x = 100;/*value resets on every entry to 100*/
x++;
x +=y;
++y;/*value is incremented on every entry */
printf("x in while loop: %d at\n", x);
}
printf("x in outer block: %d at \n", x);
return 0;
}
答案 2 :(得分:1)
这里有很多解释
让我直接回答您的问题“ 如何输出?”
while (x++ < 33) //original x
{
//int x = 100;
static int x = 100;
x++;
printf("x in while loop: %d at %p\n", x, &x);
}
我想说的是读关于static
变量和一般storage classes
答案 3 :(得分:1)
在此while循环中:
while (x++ < 33) //original x
{
int x = 100; // this x hides the original x
x++;
printf("x in while loop: %d at %p\n", x, &x);
}
在循环体中声明的x
隐藏了原始的x
(在while
循环表达式中用作计数器)。在while
循环的每次迭代中,您都将获得内部101
的相同值x
,因为while
循环的每次迭代都会创建x
的新实例(内部{{ 1}})初始化,其值为x
,并在循环主体的末尾销毁它。
我如何使其输出?
如果希望内部100
的最后一个值在x
循环的每次迭代中保持不变,则只需将内部while
设为静态:
while (x++ < 33) //original x
{
static int x = 100;
x++;
printf("x in while loop: %d at %p\n", x, &x);
}