So let's say you had to choose a number between 1 and 4... and depending on the number selected, the program will print out a colour.
- 1 - Red
- 2 - Blue
- 3 - Yellow
- 4 - Green
Sure, we can write this with a bunch of if-statements:
Code (C++)
if (num == 1) {
cout << "Red" << endl;
} else
if (num == 2) {
cout << "Blue" << endl;
} else
if (num == 3) {
cout << "Yellow" << endl;
} else
if (num == 4) {
cout << "Green" << endl;
}
Doesn't that look a little... clustered though? There is a much easier way to write this. Introducing the
switch/case statement.
Code (C++)
switch (num) {
case 1: cout << "Red" << endl; break;
case 2: cout << "Blue" << endl; break;
case 3: cout << "Yellow" << endl; break;
case 4: cout << "Green" << endl; break;
}
So the switch/case statement will read the value of "num", and go to a case based on its value. Simple enough, but it has its catches. Notice the
break; there. If that isn't there and we were at case 1... it would end up going down to case 2 and executing its code! Observe:
Code (C++)
switch (num) {
case 1: cout << "Red" << endl; break;
case 2: cout << "Blue" << endl; break;
case 3: cout << "Yellow" << endl; break;
case 4: cout << "Green" << endl; break;
}
Output
Input Number: 1
Red
Blue
This can be good however, because what if you actually wanted 1 and 2 to do the same thing? You can write a switch/case statement in this style:
Code (C++)
switch (num) {
case 1:
case 2:
//Do something
break;
}
The "default" keyword
Remember how if-statements had "else"? Switch/Case statements have their own form of this as well, known as "default". If none of the cases match the number given, it will go to the default case.
Code (C++)
switch (num) {
case 1: cout << "Red" << endl; break;
case 2: cout << "Blue" << endl; break;
case 3: cout << "Yellow" << endl; break;
case 4: cout << "Green" << endl; break;
default: cout << "Unknown" << endl; break;
}