break 문 (C++)
문은 break
표시되는 가장 가까운 바깥쪽 루프 또는 조건문의 실행을 종료합니다. 제어는 종료된 문 뒤의 문이 있는 경우 전달됩니다.
구문
break;
설명
문은 break
조건부 switch 문 및 do, for 및 while 루프 문과 함께 사용됩니다.
switch
문에서 문은 break
프로그램이 문 외부에서 switch
다음 문을 실행하도록 합니다. break
문이 없으면 일치하는 case
레이블에서 절을 비롯한 default
문의 끝까지 switch
의 모든 문이 실행됩니다.
루프에서 문은 break
가장 do
가까운 , for
또는 while
문의 실행을 종료합니다. 종료된 문 뒤에 문이 있는 경우 제어가 해당 문으로 전달됩니다.
중첩된 문 내에서 문은 break
즉시 묶는 , for
, switch
또는 while
문만 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';
}
}
In each case:
1
2
3
다음 코드는 루프 및 루프에서 를 사용하는 break
방법을 보여 주는 코드입니다do
.while
#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);
}
In each case:
0123
다음 코드에서는 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";
}
}