Selection

If

An if statement looks like this:

if (expression)
	statement;
else
	statement;

If using multiple statements, use curly brackets:

if (expression)
{
	statement;
	statement;
}
else
{
	statement;
	statement;
}

The else section is optional:

if (expression)
{
	statement;
	statement;
}

You can nest ifs! When you put an if statement inside an if statement, the else statement refers to the nearest if statement that hasn't already got an else statement.

Switch

switch is a multi-branch selection statement. You use it like this:

switch (expression) {
	case constant1:
		statements
		break;
	case constant2:
		statements
		break;
	...
	default:
		statements
}

The cases are tested in order. The value must be an integer or a constant. When a match is found the corresponding code block is executed. The default statement is executed if there are no matches. If no default is defined, and there are no matches, no action is taken.

break is one of C++'s jump statements. It can be used in loops as well as in switch statements. When it is encountered in a switch, the execution jumps to the line of code following the switch statement.

Example of switch - The Awesomeness Detector:

switch (awesomeness) {
	case 1:
		cout << "Not very awesome";
		break;
	case 2:
		cout << "Fairly awesome";
		break;
	case 3:
		cout << "Very awesome";
		break;
	default:
		cout << "Awesomeness undetected";
}