When you have to check multiple conditions, using if-else statements becomes too tiring. However here the switch statement comes to help.



There can be 4 different outputs, 3 when the user enter a correct input and a default one for any other cases.
Let’s see one of them:

 

 

Last week you learnt how to use if, else if and else statements, because of course you read Learn C programming: Conditions (if, else if, else) | Step-by-Step.

However, while you where experimenting, you noticed that things become quite tough when you want to check multiple values against the same variable.

Writing programs like the one below is driving you crazy.

Look at THAT!

I wrote variable_to_check too many times in such a tiny piece of code! It’s tiring, you know?

Using the switch statement instead, all the work becomes easier.

This method allows you to test a variable against multiple values, without having to write the entire condition each time.

It isn’t more compact then using the if statements, but it’s cleaner and easier to write.

It looks like this:

While this is the flowchart:

Switch Flowchart

What is that?!


So, let’s see it step-by-step.

  • The first line introduces the switch statement and the variable we want to test. Replace variable_to_test with the name of your variable.
  • The second line contains the first case, that is the first value against which our variable has to be tested.
    case is just a keyword like switch and if: you can’t change it or name a variable after it. value1 can only be an integer or character (you can’t use a float or a double type). Finally you must always put a comma after the value you wrote.
  • Replace code here at the third line with the code you want to run if your variable is equal to this case statement’s value.
  • After that you should write the keyword break followed by a semi-colon. Not doing it isn’t an error, but then all the cases that follow will be executed automatically, without checking their values.
  • You can write as many cases as you want: in my example there are just three.
  • At the end there’s one last keyword: default.
    If you compare the case statement to else if, then default is similar to else. Whenever the variable didn’t match any of the previous values, the code under default is run.

 

Tips and Tricks


  • Even if you can’t check if a number is greater than another using switch, you can test against a range of values in a single case. Just use this formula as value: x ... y, where x and y are respectively the start (included) and the end (included) of the range.
  • Just like else, default isn’t necessary.
  • As I’ve already said, you can also not use break: if so, when a case is executed all the following statements will be executed too, until a break is reached or the switch ends.Switch statement without breaks Switch statement with breaks

 

How does the previous example look using switch?


Does it look any better?

I definitely think so.

 

Let’s analyse today’s program


Today’s program contains some topics we already talk about multiple times, such as #include, printf and scanf. I’m not going to explain them again here, so if don’t know what they are and how they work, I recommend you this post: Learn C Programming: Variables | Step-by-Step Explanation. Otherwise, if you haven’t made your first program yet check Make Your First C Program (+ Step-by-step explanation).

//Question + options

This is a comment. Comments are parts of your code that the computer ignores during compilation and they are a good practice to remember what your program does.

There are two ways to create a comment:

  1. Using a double slash ( // ), like I did, turns every word after it on the same line in a comment.
  2. If you want a comment to consist of multiple lines, you can use /* ... */. All you have to do is put a /* where you want your comment to begin and a */ at the end.

printfs, int answer and scanfs

Make sure you read the two post I mentioned above. In short:

  • printf(“sentence + optional special characters”, values that replace special characters); allows the program to write on the command prompt
  • int answer; is a variable’s declaration, or in other words the creation of a variable;
  • scanf(“special characters that indicate the type of value to read”, & symbol + variable); allows the program to read from the command prompt

switch(answer) {

Here the switch statement begins.

Inside the brackets you must put the variable you want to test – in this case answer. You can only test int and char variables: switch doesn’t support float, double and other types.

Just like if, else or when we’re defining a function such as main(), switch doesn’t want a semicolon at the end of the line. Instead you must put all its code inside curly brackets.

case 1:/case 2:/case 3:

These three lines have the same function: telling the computer against which values it has to test the variable in switch.

If the variable’s value and the case’s value are equal, the corresponding code is run.

printf(“High five, bro\n”);

It’s the code of the first case. If the value of answer is equal to the value of the first case – 1 – this code will be executed.

break;

It’s a keyword of C. It tells the computer that it must exit the switch statement and go on to the rest of the program. Without it, if a case is executed, all the following will be execute as well, until the computer will reach a break or the end of switch.

default:

It contains a code that will be run without checking any values. Usually, it happens when none of the cases has been run, because when a case is executed the break keyword at the end of it forces the computer to exit the statement, therefore the default code is jumped. In that case default can be compared to else, but if you don’t use breaks, it will always be executed, like a piece of code outside the curly brackets.

}

This indicates the end of the switch statement.

 

Let’s translate the code


Subheader image for translation chapter


As I always do, I wrote an interpretation of today’s program in human language:

Computer, this program uses the stdio.h library

Start executing the code from main()

Print “Are you a robot? Choose an answer:” on the command prompt and then go to a new line

Leave a blank space and print “1. Yes, of course I am”. Go to a new line

Leave another blank space and print “2. No, I’m not”, then go to a new line

Now leave another blank space and print “3. You’ll never know” and go to a new line

Print “Enter a number: “

Create a variable called answer to store an integer

Wait for the user to enter a value, then assign it to answer

Now consider the variable answer and compare it to the following values

If it’s equal to 1:

Print “High five, bro!” and go to a new line

Stop considering the variable answer and jump all the following cases

If it’s equal to 2:

Print “OK, good for you” and go to a new line

Stop considering the variable answer and jump all the following cases

If it’s equal to 3:

Print “”If you say so…” and go to a new line

Stop considering the variable answer and jump all the following cases

If you’re still here, run this default code:

Print “That isn’t even an option!”, then go to a new line

If you haven’t yet, stop considering answer

The program ends here

 

C and C++ comparison


The switch statement doesn’t have any differences between C and C++. The two main differences you can notice in the code are:

  1. printf() becomes cout
  2. scanf() becomes cin >>

I explained these in previous posts, so make sure to check them out.

 

Conclusion


To sum up: the switch statements allows you to compare a variable’s value to multiple values, indicated by case statements. If one of the tests results correct, the corresponding code is run.

It’s a cleaner and faster alternative to the if/else if method, but you can only use it to check integers or characters for equality.

 

As always, feel free to write a comment below if there’s something you haven’t understood and I’ll be happy to help you, just like I do on social networks – by the way I answer to lots of people on Quora.

If you’ve liked this post and you think it might help a friend of yours, share it using the buttons you find below – Twitter, Facebook and Google+

 

Anyway, the post is finished, have a good day and we will see the next week!

From Zephyro it’s all, Bye!


Leave a Reply

%d bloggers like this: