do while循环中的continue语句

7
#include <stdlib.h>
#include <stdio.h> 
enum {false, true}; 
    
int main() 
{ 
   int i = 1; 
   do
   { 
      printf("%d\n", i); 
      i++; 
      if (i < 15) 
        continue; 
   } while (false); 
      
   getchar(); 
   return 0; 
} 

在这段代码中执行continue语句后会发生什么?

控制权会转移到哪里?


@FredLarson 因为2 < 15是真的,所以continue将被执行。 - MikeCAT
2
该(有效)结构可以通过执行程序轻松检查。 - Jarod42
1
如果你想使用 falsetrue(以及 bool),你可以 #include <stdbool.h> - DevSolar
4个回答

11
下一个语句将是while (false);,它将结束do-while循环,所以在执行getchar();之前会执行该语句。
总的来说:
do
{
    ...
    statements
    ...

    continue;   // Act as "GOTO continue_label"

    ...
    statements
    ...

continue_label:
} while (...);

如果您想尝试,请使用以下代码:
int i = 0;
do
{
    printf("After do\n");
    ++i;
    if (i < 2) 
    {
        printf("Before continue\n");
        continue;
    }
    printf("Before while\n");
} while(printf("Inside while\n") && 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

5

ISO/IEC 9899:2011, 6.8.6.2 The continue statement

[...]

(2) A continue statement causes a jump to the loop-continuation portion of the smallest enclosing iteration statement; that is, to the end of the loop body. More precisely, in each of the statements

while (/* ... */) {
/* ... */
continue;
/* ... */
contin: ;
}

do {
/* ... */
continue;
/* ... */
contin: ;
} while (/* ... */);

for (/* ... */) {
/* ... */
continue;
/* ... */
contin: ;
}

[...] it is equivalent to goto contin;

在此代码中执行 continue 语句后会发生什么?控制权会去哪里?
控制权将前往循环的末尾,即您代码中的 while (false) ,从而退出循环。

3

来自这里:

continue语句将控制权传递给最近的封闭的do语句、for语句或while语句,跳过doforwhile语句中剩余的任何语句。

因为最近的语句是while(false)语句,在执行后续循环之前,流程会到那个语句,然后退出循环。

即使在continuewhile(false)之间有其他语句,上述情况也是成立的。例如:

int main() 
{ 
   int i = 1; 
   do
   { 
      printf("%d\n", i); 
      i++; 
      if (i < 15) 
        continue;          // forces execution flow to while(false)
      printf("i >= 15\n"); // will never be executed
   } while (false); 
   ...  

这里的continue;语句意味着其后的printf语句永远不会被执行,因为执行流程将继续到最近的循环结构之一。同样,在这种情况下是while(false)

1
当您使用continue语句时,循环内部的进一步语句将被跳过,并且控制流程转到下一个迭代,这是您的情况下的“条件检查”(在for循环的情况下,它转到for循环的第三个语句,其中通常对变量进行增量/减量)。由于条件为“false”,迭代停止。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接