当增量计数器,计数器测试互换在循环语法会发生什么? [英] what happens when increment counter and test counter are interchanged in for-loop syntax?
问题描述
请解释一下为什么结果
案例1:
INT的main()
{
INT I;
对于(i = 1;我++; I< 100)
的printf(%D,我);
返回0;
}
的结果无限循环,而结果
案例2:
INT的main()
{
INT I;
对于(i = 0;我++; I< 100)
的printf(%D,我);
返回0;
}
不运行的循环甚至一度?结果
请澄清如何跨preT这种语法?
的for循环 C语言程序设计
的语法是:
为(初始化;条件;增量)
{
声明(S);
}
-
下面是控制在一个for循环流量:
-
初始步骤首先执行,只有一次。此步骤允许您声明和初始化任何循环控制变量。您不需要在这里放一个说法,只要出现一个分号。
-
接下来,评估条件。如果这是真的,则执行循环体。如果是假的,循环体不执行,只是后循环控制流跳转到下一条语句。
-
的for循环体执行后,控制流程转移备份到增量声明。这个语句可以更新任何循环控制变量。这种说法可以留空,只要分号病情后出现。
-
该条件现在又进行评估。如果这是真的,循环执行,并重复这个过程(循环体,然后增加步,然后再次条件)。在条件为假,则循环结束。
-
在第一种情况:
-
的init
设置I = 1
-
conditon
- 在这里I = 1
是真正
在C。 (后增量说明书执行后增加的值) -
体
- 执行的printf(%d个,我);
-
递增
-I< 100
这不影响i的值
。
现在在C从1到无穷大的所有值,其值是true,因此执行infinetly
在第二种情况下
-
的init
设置I = 0
-
conditon
- 在这里I = 0
(再次后增量),这是假
在C,因此循环
获得退出。
因此,它没有执行甚至一次。
For循环的流程图:
please explain why
Case 1:
int main()
{
int i;
for(i=1;i++;i<100)
printf("%d",i);
return 0;
}
results in infinite loop, whereas
Case 2:
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
Doesn't run the loop even once?
Please clarify how to interpret this kind of syntax?
The syntax of a for loop in C programming language
is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
In First Case:
init
seti = 1
conditon
- herei = 1
which istrue
in c. (Post increment increases the value after execution of statment)body
- executesprintf("%d",i);
increment
-i<100
which is not affecting the value ofi
.
Now In C for all values from 1 to infinity, its value is true, hence executing infinetly
In Second Case
init
seti = 0
conditon
- herei = 0
(again Post Increment) which isfalse
in c, therefore theloop
gets exit.
Hence it is not executing even once.
Flow diagram of For Loop :
这篇关于当增量计数器,计数器测试互换在循环语法会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!