Skip to content

section5_switch

Fábio Gaspar edited this page Jan 18, 2019 · 1 revision

The switch statement is useful when you are checking the value of a single variable.

switch(integer_expression)
{
    case integer_constant1:
        // statements
        break;
    case integer_constant2:
        // statements
        break;
    case integer_constant3:
        // statements
        break;
    default:
        // statements
        // break statement is not needed because this is the last case
}

Suppose the integer_expression is equal to integer_constant2. Each case is analyzed step by step. The first case fails, because integer_expression is not integer_constant2. But on second case the equality is verified. Therefore, the code after case integer_constant2: is executed.

Why do you need break statements?

On every case there's a break statement, expect for the default. The break statements are optional, but they are used because of the way switch works. Consider the following code and that integer_expression is equal to integer_constant2.

General syntax:

switch(integer_expression)
{
    case integer_constant1:
        printf("1 ");
        break;
    case integer_constant2:
        printf("2 ");
    case integer_constant3:
        printf("3 ");
        break;
    default:
        printf("default ");
}

The first case fails, but on the second one equality is verified, hence the printf("2") will be executed. But the printf("3") is also executed!! On a switch statement, once a case is verified, the following statements that belong to under case will also be executed. To control this, you can use break statements. Imagine that I remove the break from case integer_constant3, the output would be 2 3 default.

Example

#include <stdio.h>
int main()
{
    char op;
    printf("Operation ? (+,-,*,/) ");
    scanf("%c", &op);

    switch(op)
    {
        case '+':
            printf("Addition!\n");
            break;
        case '-':
            printf("Subtraction\n");
            break;
        case '*':
            printf("Multiplicaiton\n");
            break;
        case '/':
            printf("Division!\n");
            break;
        default:
            printf("Unknown operator!\n");
    }
}
/*OUTPUT
Operation ? (+,-,*,/) *
Multiplicaiton
*/

Exercise

  1. Make a program that simulates a basic calculator to perform addition, subtraction, multiplication and division. Consider might not be integers. You should handle division by zero and show a proper message like below.
Operation ( + , - , * , / ) ? +
First Operand ? 5
Second Operand ? 6
Result: 11.000000

Operation ( + , - , * , / ) ? /
First Operand ? 5
Second Operand ? 0
Undefined, division by zero!

Operation ( + , - , * , / ) ? !
First Operand ? 6
Second Operand ? 666
Invalid operator!