#include <stdlib.h>
#include <stdio.h>
enum {false, true};
int main()
{
int i = 1;
do
{
printf("%dn", i);
i++;
if (i < 15)
continue;
} while (false);
getchar();
return 0;
}
在该代码中执行continue
语句后会发生什么?
控制在哪里?
下一个语句将是while (false);
,它结束do-while
循环,然后执行getchar();
一般情况下:
do
{
...
statements
...
continue; // Act as "GOTO continue_label"
...
statements
...
continue_label:
} while (...);
如果你想尝试一下,你可以使用以下代码:
int i = 0;
do
{
printf("After don");
++i;
if (i < 2)
{
printf("Before continuen");
continue;
}
printf("Before whilen");
} while(printf("Inside whilen") && i < 2);
输出+注释解释:
After do // Start first loop
Before continue // Execute continue, consequently "Before while" is not printed
Inside while // Execute while
After do // Start second loop
Before while // Just before the while (i.e. continue not called in this loop)
Inside while // Execute while
ISO/IEC 9899:2011,6.8.6.2 continue语句
[…]
(2(
continue
语句导致跳转到循环继续最小封闭迭代语句的一部分;也就是说回路主体的末端。更准确地说,在的每个语句中while (/* ... */) { /* ... */ continue; /* ... */ contin: ; } do { /* ... */ continue; /* ... */ contin: ; } while (/* ... */); for (/* ... */) { /* ... */ continue; /* ... */ contin: ; }
[…]相当于
goto contin;
在该代码中执行continue语句后会发生什么?控制在哪里
循环结束时,即代码中的while ( false )
,它将退出循环。
从这里开始:
continue语句将控制权传递给最近的封闭
do
、for
、或出现在其中的while
语句,绕过do
、for
或while
语句中的任何剩余语句机身
因为其中最接近的一个是while(false)
语句,所以执行流继续到该语句,并退出循环。
即使continue
和while(false)
之间有其他语句,这也是正确的。例如:
int main()
{
int i = 1;
do
{
printf("%dn", i);
i++;
if (i < 15)
continue; // forces execution flow to while(false)
printf("i >= 15n"); // will never be executed
} while (false);
...
这里的continue;
语句意味着它后面的printf
语句永远不会被执行,因为执行流继续到最接近的一个循环结构。同样,在本例中为while(false)
。
当您使用continue语句时,循环中的其他语句将被跳过,控制将转到下一次迭代,即;条件检查";在您的情况下(在for循环的情况下,它转到for循环的第三条语句,其中通常对变量执行递增/递减操作(。由于条件是";"假";,迭代停止。