Switch Case in C Tutorial

In this section, we will learn what the switch statement is and how to use it in C.

C Switch Statement

I’m going to give you something:

  • In case this `something` is an Apple, you can eat it.
  • In case it is money, you can spend it.
  • In case it is paper, you can write on it.
  • In case it is a mobile phone, you can call with it.
  • If it wasn’t any of the cases mentioned above, your default action is to simply return that `something` back to me.

The description above can be considered as a `switch`. In this example, there’s an input and we are switching between a set of options to see which of these options matches with the input we’ve got. If there’s a match, we will run the instructions that are set for that match.

We can run the same concept in C programming via the `switch` operator.

Let’s say you’ve created a program that asks a user to insert a number range from 1 to 3:

  • In case the number was 1, the program will print the message “Hello!”.
  • In case the number was 2, the program will print the message “Welcome!”.
  • In case the number was 3, the program will print the message “Goodbye!”.
  • If the use entered a number other than these 3 numbers, the default behavior of the program is to simply print “Wrong number!”.

Now, using the switch operator, we can easily implement this algorithm.

Syntax of Switch Case:

Let’s see the structure of the `switch` statement:

switch(integer-expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

During the explanation of the example below, we will introduce each of the keywords in the `switch` statement.

C switch statement example:

#include <stdio.h>

int main() {

    int inputValue = 1;

    while( inputValue != 000){
        printf("Please enter a number from 1 to 3 or 000 for exit\n");
        //take the number from user.
        scanf("%d",&inputValue);

        switch (inputValue){
            case 1:
                printf("Hello!\n");
                break;
            case 2:
                printf("Welcome!\n");
                break;
            case 3:
                printf("Goodbye!\n");
                break;
            case 000:
                printf("Have a great time!");
                break;
            default:
                printf("Wrong number!\n");
                break;
        }
    }

    return 0;
}

Compile and run the example above and try different numbers to see different outputs.

How does the switch statement work?

In this example, after we’ve taken a number from a user via the scanf function, we assigned that number to the `inputValue` variable and then checked to see the value assigned to this variable via `switch` statement.

As you can see, the switch statement starts with the `switch` keyword followed by a pair of parentheses and within this pair we set the target value (in this example `inputValue`).

Note: in the pair of parentheses, we set any type of expression that results in an integer value.

The value in the parentheses of the switch statement is the one that will be matched against each case statement in the body of the switch to see the value of which one of them will match against the input value.

Followed by `()` is the body of the `switch` statement, which starts from the open curly brace `{` and ends with the close curly brace `}` and within this body we define the cases and their instructions.

In the example above, we have declared 4 `case` and one `default` option.

case block in switch

Each `case` keyword is one check point inside the `switch` body. This means the value declared in the parentheses of the switch statement will be matched against each `case` and if the value matched any `case`, the body of that `case` will run.

Here in the example above, each `case` is followed by an integer number.

Note: the body of a `case` starts after its colon `:` and ends before the next `case` or the `default` or ending curly brace `}` because using the `default` keyword is optional and the target `case` keyword might be the last declared `case` in the switch statement which in that case the ending curly brace `}` of the switch statement is the ending body of the last `case` statement as well.

C `break` statement in switch

Also, in the body of each `case` statement, we’ve used the keyword `break`. You’ll learn more about this keyword in the break statement section but in short, via this keyword the CPU will jump after the closing curly brace `}` of the `switch` statement and continues to run the instructions after the `switch` statement.

If you think about it, the value in the `switch` statement only matches one `case` statement and after that match, there’s no reason to check the other `case` statements, right? So for this reason, we use the `break` statement in order to stop a `switch` statement from checking the other `case` statements, which is a waste of CPU’s time at this point!

For example, if we enter the value 2 in the example above, the first `case` statement obviously doesn’t match the value 2, so the body of this `case` won’t run. Moving on to the next `case` statement, it does match the value entered by us. So the body of this statement will run. But now that the value matched, there’s no reason to continue to the next `case` statement, right? For this reason, we used the `break` keyword to remind the CPU that there’s no need to run the other `case` statements in the `switch` and it can move on to the instructions after the `switch` statement now.

Omitting the `break` statement in Switch

We can also remove the use of `break` keyword which in that case the entire body of the rest of `case` statements will run even if the value for each `case` statement doesn’t match the actual value assigned to the `switch` statement.

Example: omitting the `break` statement in Switch

#include <stdio.h>

int main() {

    int inputValue = 1;

    while( inputValue != 000){
        printf("Please enter a number from 1 to 3\n");
        //take the number from user.
        scanf("%d",&inputValue);

        switch (inputValue){
            case 1:
                printf("Hello!\n");

            case 2:
                printf("Welcome!\n");

            case 3:
                printf("Goodbye!\n");

            case 000:
                printf("Have a great time!");

            default:
                printf("Wrong number!\n");

        }
    }

    return 0;
}

Now compile and run the example above and enter a value like 2. You’ll see the body of the first `case` statement will not match, obviously! But the second `case` statement will match the entered value and other than the execution of the body of the second `case` statement, you’ll see the body of the rest of `case` statements and the `default` statement are executed as well. This is because we didn’t use the `break` keyword in any of these bodies to stop the execution.

C `default` statement in switch

In each switch statement, there’s an optional statement called `default` statement. If none of the `case` statement within the body of a switch matched the input value of that switch, then the default statement will run.

C Multiple `case` statements and one body:

There are times that we want to run only one body for multiple cases. For example, in the example above we want to print `Hello!` if the user entered 1 or 10 or 1000.

In such a case, we can declare 3 `case` statement without defining the body of the first two `cases` and only define the body of the third `case` statement. This way, we’re creating one block for multiple cases.

Example: C multiple case statement with one body

#include <stdio.h>


int main() {

    int inputValue = 1;

    while( inputValue != 000){
        printf("Please enter a number from 1 to 3\n");
        //take the number from user.
        scanf("%d",&inputValue);

        switch (inputValue){
            case 1:
            case 10:
            case 1000:
                printf("Hello!\n");
                break;
            case 2:
                printf("Welcome!\n");
                break;
            case 3:
                printf("Goodbye!\n");
                break;
            case 000:
                printf("Have a great time!");
                break;
            default:
                printf("Wrong number!\n");
                break;
        }
    }

    return 0;
}

Now run the example above, and you’ll see that if you enter 1 or 10 or 1000, the output will be “Hello!”.

This is because 1, 10, 1000 cases share the same body.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies