c++中的break,continue,goto語句


一、break語句
1、用法:
出現在switch語句或循環體中,使程序從循環體和switch語句內跳出,繼續執行邏輯上的下一條語句,break語句不宜用在別處。
2、實例:

#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
    int i, n;
    for (i = 1; i <= 3; i++)
    {
        cout << "請輸入n:" << endl;
        cin >> n;
        if (n < 0)
        break;
        cout << "n=" << n << endl;
    }
    cout << "程序結束!" << endl;
    return 0;

}

3、運行結果

輸入負數則程序會結束:
二、goto語句:
1、用法:
格式:goto 語句標號 在不需要任何條件的情況下直接使程序跳轉到該語句標號所標識的語句去執行,語句標號應該放在語句的最前面,並用冒號:與語句分開
2、實例:


#include<iostream>
using namespace std;
int main()
{
    int i, n;
    for (i = 1; i <= 3; i++)
    {
        cout << "請輸入n:" << endl;
        cin >> n;
        if (n < 0)
        goto end;
        cout << "n=" << n << endl;
    }
    end:cout << "程序結束!" << endl;
    return 0;
}

3運行結果:
當輸入一個負數后,程序跳轉到goto的語句標號end所標識的語句去執行,繼而程序結束

braek與goto:
雖然都可以終止整個循環的執行,但二者有着本質區別:goto可以向任意方向跳轉,可以控制流程跳轉到程序中任意指定的語句位置;而break語句只限定流程跳轉到循環語句之后的第一條語句去執行。 (goto語句的使用會破壞程序的結構,應該少用或不用,但是如果在一個多重循環的循環體中使執行流程跳出這個多重循環,用break語句難以直接做到,而goto語句則派上用場)
三、continue語句
1、用法:
當在循環體中遇到continue語句時,程序將跳過continue語句后面尚未執行的語句,開始下一次循環,即只結束本次循環的執行,並不終止整個循環的執行。
2、實例:

#include<iostream>
using namespace std;
int main()
{
    int i, n;
    for (i = 1; i <= 3; i++)
    {
        cout << "請輸入n:" << endl;
        cin >> n;
        if (n < 0)
        continue;
        cout << "n=" << n << endl;
    }
    cout << "程序結束!" << endl;
    return 0;
}

3、運行結果:
當輸入負數后,程序跳過該次循環continue后面的語句開始了下一次循環


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM