📜  C中break和continue语句的区别

📅  最后修改于: 2021-09-12 11:01:40             🧑  作者: Mango

在本文中,我们将讨论C 中 breakcontinue语句之间的区别。它们是同一种类型的语句,用于改变程序的流程,但它们之间仍有一些区别。

break 语句该语句终止最小的封闭循环(即, while 、do-while、for 循环或 switch 语句)。下面是说明相同的程序:

C
// C program to illustrate the
// break statement
#include 
  
// Driver Code
int main()
{
  
    int i = 0, j = 0;
  
    // Iterate a loop over the
    // range [0, 5]
    for (int i = 0; i < 5; i++) {
  
        printf("i = %d, j = ", i);
  
        // Iterate a loop over the
        // range [0, 5]
        for (int j = 0; j < 5; j++) {
  
            // Break Statement
            if (j == 2)
                break;
  
            printf("%d ", j);
        }
  
        printf("\n");
    }
  
    return 0;
}


C
// C program to illustrate the
// continue statement
#include 
  
// Driver Code
int main()
{
  
    int i = 0, j = 0;
  
    // Iterate a loop over the
    // range [0, 5]
    for (int i = 0; i < 5; i++) {
  
        printf("i = %d, j = ", i);
  
        // Iterate a loop over the
        // range [0, 5]
        for (int j = 0; j < 5; j++) {
  
            // Continue Statement
            if (j == 2)
                continue;
  
            printf("%d ", j);
        }
  
        printf("\n");
    }
  
    return 0;
}


输出:
i = 0, j = 0 1 
i = 1, j = 0 1 
i = 2, j = 0 1 
i = 3, j = 0 1 
i = 4, j = 0 1

说明:在上面的程序中,当变量j的值变为2时,内部 for 循环总是结束。

continue 语句该语句跳过循环语句的其余部分并开始循环的下一次迭代。下面是说明相同的程序:

C

// C program to illustrate the
// continue statement
#include 
  
// Driver Code
int main()
{
  
    int i = 0, j = 0;
  
    // Iterate a loop over the
    // range [0, 5]
    for (int i = 0; i < 5; i++) {
  
        printf("i = %d, j = ", i);
  
        // Iterate a loop over the
        // range [0, 5]
        for (int j = 0; j < 5; j++) {
  
            // Continue Statement
            if (j == 2)
                continue;
  
            printf("%d ", j);
        }
  
        printf("\n");
    }
  
    return 0;
}
输出:
i = 0, j = 0 1 3 4 
i = 1, j = 0 1 3 4 
i = 2, j = 0 1 3 4 
i = 3, j = 0 1 3 4 
i = 4, j = 0 1 3 4

说明:在上面的程序中,当变量j的值变为2时,内部 for 循环总是跳过迭代。

break 和 continue 语句之间的表格区别

Break Statement Continue Statement
The Break statement is used to exit from the loop constructs. The continue statement is not used to exit from the loop constructs.
The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.
When a break statement is encountered then the control is exited from the loop construct immediately. When the continue statement is encountered then the control automatically passed from the beginning of the loop statement.
Syntax:
break;
Syntax:
continue;

想要从精选的视频和练习题中学习,请查看 C 基础到高级C 基础课程。