There is another way to write conditionals in C++, and most other programming languages. It is called the switch statement. They’re most useful when we have a variable, and we want to do different things depending on the value of that variable.
Switch statements look something like this:
#include <iostream>
using namespace std;
int Day{3};
int main(){
switch (Day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
}
}
In this example, we’re switching on the value of Day
. Its value is 3
, so we trigger the case 3:
scenario, logging out Wednesday
:
Wednesday
If we want multiple values to trigger the same action, the syntax looks like this:
#include <iostream>
using namespace std;
int Day{6};
int main(){
switch (Day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 6:
case 7:
cout << "Weekend";
}
}
Here, we’re logging out Weekend
if the value of Day
is either 6
or 7
. It is, so we get the expected output:
Weekend
This is an example of fallthrough, a quirky characteristic of switch statements. In this case, the fallthrough was desired, but it’s often a source of bugs.
break
The inclusion of the break
keyword in the previous examples is to prevent fallthrough, which is the default behavior of switch statements.
Let's take a look at what happens if we don’t include the break
statements:
#include <iostream>
using namespace std;
int Day{1};
int main(){
switch (Day) {
case 1:
cout << "Monday";
case 2:
cout << "Tuesday";
case 3:
cout << "Wednesday";
}
}
Once a case
statement is triggered, every subsequent case
statement is also triggered, until we either reach the end of the switch
statement or encounter a break
instruction.
In this scenario, because the first case
was triggered, and we have no break
statements, the code in every case was executed. This generated the following output:
MondayTuesdayWednesday
Fallthrough behavior is rarely useful, but it remains the default implementation of switch statements in C++, and most other programming languages.
So, we should be mindful of it and generally remember that, in most scenarios, we’ll need to add break
s to our switch
statements.
default
daseSwitch statements can have a default
case, which is activated in all scenarios, unless a previously activated case triggered a break
:
#include <iostream>
using namespace std;
int Day{3};
int main(){
switch (Day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
default:
cout << "Something else";
}
}
Something else
— First Published
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way