Table of Contents
The break statement immediately terminates the nearest enclosing loop or switch statement. Program execution continues with the first statement following that loop or switch.
In a switch statement, break is commonly used at the end of each case to prevent execution from continuing into subsequent cases.
Source Code #
#include <iostream>
int main()
{
int day = 2;
switch (day)
{
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
case 3:
std::cout << "Wednesday\n";
break;
default:
std::cout << "Invalid day\n";
break;
}
std::cout << "Switch completed.\n";
return 0;
}
Output #
Tuesday
Switch completed.
Explanation #
- The
breakstatement immediately terminates the nearest enclosingswitchor loop. - When
dayis2,case 2is selected and"Tuesday"is printed. break;then terminates theswitchstatement.- Execution continues with the statement following the
switchblock. - Without
break, execution could continue into the statements of subsequent cases, resulting in fallthrough. - A
breakstatement affects only the nearest enclosing loop orswitchstatement. breakdoes not terminate the entire program; execution continues normally after the enclosing construct.return 0;terminates the program successfully.