A switch statement executes statements based upon the value of a variable. It is useful to replace a series of if statements, if the if statements are all looking for an equality value.
The general form of this is below:
switch (variable)
{
case 0:
// do things where variable equals 0
break; // not required, but will keep doing things until finds a break
case value1:
// do things where variable equals value1
break;
case value2:
// do things where variable equals value2
break;
case value3:
// do things where variable equals value3
break;
default:
// if there are no matches, you can optionally do something else
}
Your variable must be an integer value, and must be enclosed in parentheses. The case values must be integers as well. It doesn’t have to be a variable per say, however, it does need to have an integer value if it is part of an equation.
The break
keyword/statement is optional. It will exit the program flow from the switch as soon as it is read.
No braces are needed around the case blocks.
Let’s look at some examples:
// example with multiple case statements for a given block.
switch ( dayOfTheWeek )
{
case 1: cout << "Monday" << endl; break;
case 2: cout << "Tuesday" << endl; break;
case 3: cout << "Wednesday" << endl; break;
case 4: cout << "Thursday" << endl; break;
case 5: cout << "Friday" << endl; break;
case 0:
case 6:
cout << "It's the weekend, who cares." << endl;
break;
default:
cout << "Invalid data present." << endl;
}
The Switch Statement in C++ was originally found on Access 2 Learn