📜  C中break和Continue语句之间的区别

📅  最后修改于: 2021-05-25 22:02:34             🧑  作者: 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基础课程》。