My previous blog post looked at If, Else and Else If statements which work, however C++ also has a tidier approach called switch statements.
In the below example I have defined a character variable called response, initialised with the character ‘y’. I am then taking input and storing this input in the response variable.
char response = 'y'; cin >> response;
The switch is then run against the response variable, with defined switch cases (which act like if statements).
switch (response) { case ' ' : code to run if case matched; break; case ' ' : code to run if case matched; break; }
The cases for the switch statement are all including in one set of curly braces from the switch statement. The case is defined using the keyword case and then the pattern to match.
case 'pattern_to_match';
Then the code to run, which can be multiple lines and finally a break; to break out of the switch cases being checked.

In this example I have defined 4 cases:
- Y
- y
- N
- n
These check to see if the input response matches Y, y, N or n then run the appropriate code. But what if the user inputs something other than one of these characters? This would be captured by the default which is a bit like the else of the if / else if / else statements.
Switch statements allow for a tidier and in my opinion easier to read approach to handling paths a program can take.
You must be logged in to post a comment.