Yad*_*esh 3 c while-loop variable-declaration
据我说,while循环应该是无限的,但它只运行三次
main()
{
int i=3;
while(i--)
{
int i=100;
i--;
printf("%d..",i);
}
}
Run Code Online (Sandbox Code Playgroud)
它输出 99..99..99
但据我说,它应该运行无限次,因为每次控制进入循环时它获得值100.因此它永远不会达到零.只是为了实验我替换int i=100;了 i=100;in while循环,现在它运行无限次..WHY ???
变量iin 与循环内定义while(i--)的变量不同i.
基本上是int i = 100 阴影你前面int i = 3和内部的块while 是指一个新的变量.
在一天结束时,我发现没有合理的情况你需要做这样的事情.
i检查条件的变量是您在main()循环内部声明的变量.
两者都是你将它们混为一谈的不同变量,编译器不会像你一样容易混淆.
内循环i是指一个你内心的声明{ },但外面{ }的i指的是一个中声明main()
while(i--)
{
int i=100; // gets created every time the loop is entered
i--;
printf("%d..",i);
} // the i in the loop keeps getting destroyed here
Run Code Online (Sandbox Code Playgroud)
你为什么不尝试:
while(i--)
{
{
int i=100; //Visible only in this scope
i--;
printf("inner i=%d..",i);
} //gets destroyed here
printf("\nouter i=%d..\n",i);
}
Run Code Online (Sandbox Code Playgroud)