简体   繁体   English

为什么第一个是无限循环?

[英]Why is the first one an infinite loop?

I'm confused.. After it prints the first c, which is 1, then c became 2 then it's supposed to print c, which is 2.. int c = 1;我很困惑.. 在它打印第一个 c 后,即 1,然后 c 变为 2 然后它应该打印 c,即 2.. int c = 1;

while (c<=10)
    printf("%d\n", c);
    c = c + 1;   

while (c<=10)
{
    printf("%d\n", c);
    c = c + 1;
}

When a While loop isn't followed by当没有While循环时

{
}

The next statement is considered only to be part of the loop So your code runs the while loop indefinitely printing value of c since the condition for the while loop to run is always true enclose the print and increment statement in curly braces!下一条语句仅被视为循环的一部分因此您的代码运行 while 循环无限期地打印 c 的值,因为 while 循环运行的条件始终为真,将打印和增量语句括在花括号中!

这是因为缩进块周围没有花括号,所以只有printf是 while 的一部分。

For while loop without the brace it takes single statement after the while loop.对于没有大括号的 while 循环,它在 while 循环之后需要单个语句。

So in the first while loop, the while takes only the printf statement.所以在第一个 while 循环中,while 只接受 printf 语句。

If it is enclosed in braces, it takes that as a block of statement.如果它包含在大括号中,则将其视为语句块。 If it is not enclosed in braces it takes only one statement.如果它没有用大括号括起来,它只需要一个语句。

So, it will not increase the value of C.因此,它不会增加 C 的值。

It is because if you dont use {} The while applis only on the first line, that was you have something like这是因为如果你不使用 {} while 仅在第一行应用,那是你有类似的东西

while (c<=10)
    printf("%d\n", c);

c never changes and the loop runs forever c 永远不会改变并且循环永远运行

You are only looping over the print statement and the variable is not getting incremented.您只是在打印语句上循环,并且变量没有增加。

c = c + 1;

Is not called.不叫。 The { } define the scope of the while loop not the tab character. { }定义 while 循环的范围而不是制表符。

Change:改变:

while (c<=10)
printf("%d\n", c);
c = c + 1;   

to:到:

while (c<=10){
    printf("%d\n", c);
    c = c + 1;   
}

The reason is that if there is no brackets after while, then only the first instruction right after it is executed.原因是如果 while 后没有括号,则只有紧随其后的第一条指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM