break 문(C++)

문은 break 표시되는 가장 가까운 바깥쪽 루프 또는 조건문의 실행을 종료합니다. 제어는 종료된 문 뒤의 문이 있는 경우 전달됩니다.

구문

break;

설명

break 은 조건 switch 문 및 , for및 루프 문과 while 함께 do사용됩니다.

switch 문에서 이 문은 break 프로그램이 문 외부에서 switch 다음 문을 실행하도록 합니다. break 문이 없으면 절을 포함하여 default 일치하는 case 레이블에서 문 끝까지의 switch 모든 문이 실행됩니다.

루프에서 문은 break 가장 가까운 바깥쪽 do또는 forwhile 문의 실행을 종료합니다. 종료된 문 뒤에 문이 있는 경우 제어가 해당 문으로 전달됩니다.

중첩된 문 내에서 문은 break 즉시 묶는 , for또는 switchwhile 문만 do종료합니다. 또는 goto 문을 사용하여 return 더 깊이 중첩된 구조체에서 제어를 전송할 수 있습니다.

예시

다음 코드는 루프에서 for 문을 사용하는 break 방법을 보여줍니다.

#include <iostream>
using namespace std;

int main()
{
    // An example of a standard for loop
    for (int i = 1; i < 10; i++)
    {
        if (i == 4) {
            break;
        }
        cout << i << '\n';
    }

    // An example of a range-based for loop
int nums []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for (int i : nums) {
        if (i == 4) {
            break;
        }
        cout << i << '\n';
    }
}
1
2
3
1
2
3

다음 코드는 루프 및 do 루프에서 while 사용하는 break 방법을 보여줍니다.

#include <iostream>
using namespace std;

int main() {
    int i = 0;

    while (i < 10) {
        if (i == 4) {
            break;
        }
        cout << i << '\n';
        i++;
    }

    i = 0;
    do {
        if (i == 4) {
            break;
        }
        cout << i << '\n';
        i++;
    } while (i < 10);
}
0
1
2
3
0
1
2
3

다음 코드는 switch 문에서 사용하는 break 방법을 보여줍니다. 각 사례를 개별적으로 처리하려는 경우 모든 경우에 사용해야 break 합니다. 사용하지 break않으면 코드 실행이 다음 사례로 넘어가게 됩니다.

#include <iostream>
using namespace std;

enum Suit{ Diamonds, Hearts, Clubs, Spades };

int main() {

    Suit hand;
    . . .
    // Assume that some enum value is set for hand
    // In this example, each case is handled separately
    switch (hand)
    {
    case Diamonds:
        cout << "got Diamonds \n";
        break;
    case Hearts:
        cout << "got Hearts \n";
        break;
    case Clubs:
        cout << "got Clubs \n";
        break;
    case Spades:
        cout << "got Spades \n";
        break;
    default:
          cout << "didn't get card \n";
    }
    // In this example, Diamonds and Hearts are handled one way, and
    // Clubs, Spades, and the default value are handled another way
    switch (hand)
    {
    case Diamonds:
    case Hearts:
        cout << "got a red card \n";
        break;
    case Clubs:
    case Spades:
    default:
        cout << "didn't get a red card \n";
    }
}

참고 항목

점프 문
키워드
continue 문