Table of Contents
The switch statement provides a multi-way selection mechanism based on the value of an expression. It compares the expression against a sequence of case labels and executes the statements associated with the matching label.
The break statement is commonly used to terminate a case and prevent execution from continuing into the following cases. A default label can be used to handle values that do not match any of the specified cases.
Source Code #
#include <iostream>
int main()
{
int day = 3;
switch (day)
{
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
case 3:
std::cout << "Wednesday\n";
break;
case 4:
std::cout << "Thursday\n";
break;
default:
std::cout << "Invalid day\n";
break;
}
return 0;
}
Output #
Wednesday
Explanation #
- The
switchstatement evaluates the expressionday. - Each
caselabel specifies a possible value that can match theswitchexpression. - When the value of
daymatchescase 3, the statements associated with that case are executed. - The
breakstatement terminates theswitchstatement and transfers execution to the statement following it. - Without
break, execution can continue into subsequentcaselabels. This behavior is known as fallthrough. - The
defaultlabel is executed when none of thecaselabels match the value of theswitchexpression. - A
switchstatement is useful when selecting between multiple discrete constant values. return 0;terminates the program successfully.