C++: Switch Statements

Sometimes when creating a C++ program, you run into a situation in which you want to compare one thing to a number of other things. Let's say, for example, that you took a character from the user and wanted to compare this to a number of characters to perform different actions. For now, let's just say that you have three commands which operate from the keys: 'h', 'e', and 'q'.

We can use an if-statement to check equality to 'h', 'e', and 'q' - remember that we use single quotes because we're dealing with chars, not strings. So let's just write the code in the way we're used to (and let's wrap a while loop around it so it keeps getting a character and acting upon what it was, because that makes our program slightly better and easier to test), using if-statements, like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

int main()
{
	char ch; //Create a char variable called 'ch'

	while(true)
	{
		cout << ">"; //Output a prompt character to let the user know that they should type here...
					 //even though we only want one character to be entered in this program
		cin >> ch; //Get a character and put it in 'ch'

		if(ch == 'h') //If the character entered is 'h'
		{
			cout << "[Help] Commands: 'h', 'e', 'q'.\n"; //Do the 'h' stuff
		}
		else if(ch == 'e') //If the character entered is 'e'
		{
			cout << "[Execute] Add custom functionality here.\n"; //Do the 'e' stuff
		}
		else if(ch == 'q') //If the character entered is 'q'
		{
			cout << "[Quit] Exiting upon another keypress.\n"; //Do the 'q' stuff
			break; //Break from the (otherwise) infinite loop
		}

		cout << "\n"; //Output a new line, purely for presentation
	}

	return 0;
}

This program should be something you're comfortable with creating by this point, however your programmer instincts should also be kicking in and telling you that you shouldn't be repeating so much code here. One of the core principles of object orientated programming is DRY: Don't Repeat Yourself. In this program we're having to repeat a lot of code for the "else if"s including using ch == every time we're doing a comparison.

The solution to this "problem" is what this tutorial is all about: switch statements. These are essentially just a really nice way to compare one expression to a bunch of different things. They are started via the switch keyword, and from there comparisons are made using a case: syntax. It isn't easily described in words, so take a look at the syntax below:

1
2
3
4
5
6
7
8
9
switch(expression_to_evaluate)
{
	case value_to_check_against:
		//Stuff to do
		break; //Break out of the switch statement
	case value_to_check_against_two:
		//Stuff to do
		break; //Break out of the switch statement
}

The different cases essentially act as many if/else-ifs in a chain, and an "else" type clause can be specified by using default:

1
2
3
4
5
6
7
8
9
10
11
switch(expression_to_evaluate)
{
	case value_to_check_against:
		//Stuff to do
		break; //Break out of the switch statement
	case value_to_check_against_two:
		//Stuff to do
		break; //Break out of the switch statement
	default:
		//Stuff to do if none of the cases match
}

This type of functionality should be reasonably easy to understand with if-statements securely under your belt, and so if you're feeling brave - try porting the basic program we created at the start of this tutorial to use if-statements. If you're not quite that brave, the cleaner and neater switch version of the code is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

using namespace std;

int main()
{
	char ch; //Create a char variable called 'ch'

	while(true)
	{
		cout << ">"; //Output a prompt character to let the user know that they should type here...
					 //even though we only want one character to be entered in this program
		cin >> ch; //Get a character and put it in 'ch'

		switch(ch)
		{
			case 'h': //If the character entered is 'h'
				cout << "[Help] Commands: 'h', 'e', 'q'.\n"; //Do the 'h' stuff
				break;
			case 'e': //If the character entered is 'e'
				cout << "[Execute] Add custom functionality here.\n"; //Do the 'e' stuff
				break;
			case 'q': //If the character entered is 'q'
				cout << "[Quit] Exiting upon another keypress.\n"; //Do the 'q' stuff
				break;
		}

		if(ch == 'q') { break; } //Not extremely efficient, but another check outside 'switch' to break from the loop if ch was 'q'

		cout << "\n"; //Output a new line, purely for presentation
	}

	return 0;
}