Learning C++: Switch Statements

An example "Hello World" in C++

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.

C++ Switch Statements
C++ Switch Statements

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.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.