OverIQ.com

The Switch statement in C

Last updated on July 27, 2020


The Switch Statement #

The switch statement is a multi-directional statement used to handle decisions. It works almost exactly like the if-else statement. The difference is that the switch statement produces a more readable code in comparison to if-else statement. Also, sometimes it executes faster than the if-else counterpart. The syntax of switch statement is as follows:

Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
switch(expression)
{
    case constant1:
        statement1;
        statement2;
        ...
    case constant2:
        statement3;
        statement4;
        ...
    case constant3:
        statement5;
        statement6;
        ...
    default:
        statement7;
        ...
}

The expression in the switch statement can be any valid expression which yields an integral value. The expression can also be a character constant ( because all characters are eventually converted to an integer before any operation ) but it can’t be floating point or string.

constant1, constant2 and so on following the case keywords must be of integer type (like int, long int etc ) or character type. It can also be an expression which yields an integer value. Each case statement must have only one constant. Multiple constants in the single case statement are not allowed. Further, all case constants must be unique.

After each case constant, we can have any number of statements or no statement at all. If there are multiple statements then you don't need to enclose them with the braces ({}).

Here are some valid switch expressions and case constants.

1
2
3
int a,b,c;
float, f1, f2;
char ch1, ch2;

Valid switch expression #

1
2
3
4
5
6
switch(a)
switch(a + b + c)
switch(ch1 + a)
switch(a < b)
switch(my_func(12))
switch('a')

Invalid switch expression #

1
2
3
switch(a + 12.2) // expression must yield an integer value not double or float.
switch(f1)       // same reason as above.
switch("string") // string is not allowed.

Valid case constant #

1
2
3
4
case 1
case 1 + 2
case 'a'
case 'a' < 'b'

Invalid case constant #

1
2
3
4
5
case "string"  // string constants are not allowed
case 1.2       // floating point constants are not allowed
case a         // variables are not allowed
case a + b     // variables are not allowed
case 1,2,3     // each case must contain only one constant</pre>

How it works:

First of all, the expression following the switch is evaluated, then the value of this expression is compared against every case one by one. If the value of the expression matches with any case constant then the statements under that case are executed. If the value of the expression does not match any case constants then the statements under default are executed. The default statement is optional if omitted and no case matches then no action takes place.

Let's now see the switch statement in action.

The following program asks the user to enter a number and prints the message accordingly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<stdio.h>

int main()
{
    int i, sum;

    printf("Enter a number: ");
    scanf("%d", &i);

    switch(i)
    {
        case 1:
        printf("Number is one\n");

        case 2:
        printf("Number is two\n");

        case 3:
        printf("Number is three\n");

        case 4:
        printf("Number is four\n");

        default:
        printf("something else\n");
    }

    // return 0 to operating system
    return 0;
}

Expected Output:

1
2
3
4
5
Enter a number: 2
Number is two
Number is three
Number is four
something else

How it works:

Let’s say user entered 2. Then the switch expression is evaluated, the value of the expression is compared against every case. When a match is found, all statements under that case are executed. In our case, the value of the 2nd case matches the value of the expression (i.e 2). As a result, all the statements under that case are executed. The important thing to note is that that statements under case 3, case 4 and default are also executed. This is known as falling through cases and this is how the switch statement works by default.

Most of the time, we don't want the control to fall through the statements of all the cases, instead, we want to just execute the statements under the matching case and break out of the switch statement. We can achieve this using the break statement. When the break statement is countered inside the switch statement, the program control immediately breaks out of the switch and resumes execution with the statement following it.

Let's rewrite our previous program, but this time, only the statements of the matching case will be executed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<stdio.h>

int main()
{
    int i, sum;

    printf("Enter a number: \n");
    scanf("%d", &i);

    switch(i)
    {
        case 1:
            printf("Number is one\n");
            break;
        case 2:
            printf("Number is two\n");
            break;
        case 3:
            printf("Number is three\n");
            break;
        case 4:
            printf("Number is four\n");
            break;
        default:
            printf("something else\n");
    }

    // return 0 to operating system
    return 0;
}

Expected Output:

1st run:

1
2
3
Enter a number:
3
Number is three

2nd run:

1
2
3
Enter a number:
11
something else

A Simple Calculator using the Switch statement #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<stdio.h>

int main()
{
    int a =1, b = 2;
    char op;

    printf("Enter first number: ");
    scanf("%d", &a);

    printf("Enter second number: ");
    scanf("%d", &b);

    printf("Enter operation: ");
    scanf(" %c", &op);

    switch(op)
    {
        case '+':
            printf("%d + %d = %d", a, b, a+b);
            break;
        case '-':
            printf("%d - %d = %d", a, b, a-b);
            break;
        case '*':
            printf("%d * %d = %d", a, b, a*b);
            break;
        case '/':
            printf("%d / %d = %d", a, b, a/b);
            break;
        default:
            printf("Invalid Operation \n");
    }

    // return 0 to operating system
    return 0;
}

Expected Output:

1st run:

1
2
3
4
Enter first number: 34
Enter second number: 13
Enter operation: *
34 * 13 = 442

2nd run:

1
2
3
4
Enter first number: 441
Enter second number: 981
Enter operation: +
441 + 981 = 1422

How it works:

In line 5, two variables a and b of type int are declared. These variables will store the numbers entered by the user.

In line 6, a variable op of type char is declared. This will store the sign of the operator entered by the user.

In lines 8-9, the program asks the user to enter the first number. The entered number is stored in the variable a.

In lines 11-12, the program again asks the user to enter the second number. The entered number is stored in the variable b.

In lines 14-15, the program asks the user to enter the symbol of the operation he/she wants to perform on the two numbers. The entered symbol is assigned to the variable op.

In lines 17-33, we have a switch statement. The variable op is used as an expression in the switch statement. The value of op is then compared against every case one by one. If the value of the op matches any case then the statements in that case are executed and the break statement causes the program control to break out of the switch statement.