The Switch statement in C

The switch statement is a multi-directional statement used to handle decisions. The switch statement works very much like if... else statement. It is restricted in the way a particular choice is selected, but where it does apply, it provides a very neat and easily understood solution. It’s syntax is:

Syntax:

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 expression which yields an integer value. For example, integer constant, arithmetic expression, function call returning an integer value, logical, relational, bitwise expressions etc. Expression can also be a character constant because all characters are eventually converted to an integer before any operation. Note that expression can’t be floating point or string.

constant1, constant2 and so on following case keyword must be a constant or constant expression of integer or character type only nothing else. Each case statement must have only one constant , multiple constants are not allowed.

The case can be followed by any number of statements. It is possible that case has no statement under it. If case is followed by multiple statements, then it is not necessary to enclose them in curly braces ( {} ).

Here are valid switch expression and case constants.

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

Valid switch expression

switch(a)
switch(a+b+c)
switch(ch1+a)
switch(a<b)
switch(my_func(12))
switch('a')

Invalid switch expression

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

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

Invalid case constant

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 // case must contain only one constant

How it works

First of all the expression following 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 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. default is optional if omitted and no case matches then no action takes place.

Let’s now see the switch statement in action.

#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");
    }

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

Enter a number: 2
Number is two
Number is three
Number is four
something else

How it works

How it works

Let’s say user entered 2. Then the switch expression is evaluated, the value of the expression i.e 2 is compared against every case. When a match is found, all statements under that case are executed. In our case, the value of 2nd case matches the value of the expression, as a result, all the statements under that case are executed. The important thing to note is that statement under case 3, case 4 and default are also executed. This is known as falling through cases and this is the 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, then the statements following the break are not executed and control immediately comes out of the switch statement.

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

#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");
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1st run:

Enter a number:
3
Number is three

2nd run:

Enter a number:
11
something else

A Simple Calculator using switch statement

#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);

    fflush(stdin);

    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");
    }

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

1st run:

Enter first number: 34
Enter second number: 13
Enter operation: *
34 * 13 = 442

2nd run:

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.

In line 6, a variable op is declared of type char.

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 line 14, fflush(stdin) function is called to consume the newline character (which was entered while inputting the second number) in the buffer.  This call is necessary otherwise the scanf() call in line 17, would read newline character and does not wait for user input.

In lines 16-17, 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 variable op

In lines 19-35,  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 statements in only that case will be executed. And the break statement causes the control to break out of the switch statement as soon as all the statements under the matching case are executed.