Users Online

· Guests Online: 92

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Switch statement in C

Switch statement in C

We use the switch statement in C to make a choice. The switch-case-default mechanism is very convenient where multiple outcomes are possible.

Syntax


switch(expression)
{
    case <integral constant 1>: statement 1; [break];
    case <integral constant 2>: statement 2; [break];

    ....

    case <integral constant n>: statement n; [break];
    [default: default statement;]
}

The switch tries to match an expression to a number of possible values, called cases. If no case matches, the mechanism executes the default statement.

Simplified switch statement flowchart

Switch statement simplified flow chart

The example is simplified for two reasons:

  1. It assumes that the statement of each case has a break. We will go into detail about this in a minute.
  2. It also assumes that the implementation checks all cases consecutively. In reality most implementations will use hash tables or other methods to reduce the number of compares and increase the efficiency.

If you don’t understand what these mean, don’t worry, just accept that the switch works as described.

Simple switch-case-default example

int direction = 4;
switch(direction)
{
    case 1: printf("North"); break;
    case 2: printf("East"); break;
    case 3: printf("South"); break;
    case 4: printf("West"); break;
    default: printf("Unknown direction");
}

In this example we test the variable “direction” against the four directions. If we find a match we print the corresponding direction. If no match is found the default statement executes and says “Unknown direction”.

In the example above we will print West.

Specifics and restrains

  • The switch expression must be put in parenthesis ().
  • The data type of the switch and case statements must have an integer value equivalent. In other words it must be one of the following: int(doesn't matter if it is short/long/signed/unsigned), charenum.
    char and enum are allowed, because their values are represented as ints for the computer.
  • Each case must be a precompile constant.
  • Each case must have a unique value. No duplicates are allowed.
  • If some case is executed, the execution continues until a break is reached.
    If the current case does not contain a break, the execution continues with the statements in the next case(or default) even if their condition is not met.

Example, combining cases

char symbol;
printf("Enter a symbol: ");
scanf("%c", &symbol);
switch(symbol)
{
    case '-':
    case '+':
    case '*':
    case '/':
    case '=': printf("This is a symbol from the simple arithmetics."); break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': printf("This is a digit."); break;
    default: printf("I don't know this symbol. Probably a letter..."); break;
}
printf("\n");

In this example we combine the cases, because we just want to point out the group where our symbol belongs. For instance, if we input *, the third case will match. Its statement is empty and it does not have a break, the execution continues with the next case  ‘/’. Here we continue with the next one ‘=’ and we print the message. Then we have a break, which means that the execution of the switch statement is stopped right here. The next statement to be executed is the printf("\n"); after the closing bracket of the switch.

Switch statement – duplicated values

As we already said, all cases must have a unique value. This is not always obvious.
For example, the character type in C is represented with an integer code by the ASCII table. The code of the symbol ‘A’ is 65. So, could we have the following switch statement?

char symbol;
....
switch(symbol)
{
    case 'A': printf("A"); break;
    case 65: printf("65"); break;
}

The answer is NO. Both values are the same for the compiler and it will mark this as a duplicate.

Examples download

You can download these examples from here: switch-statement-examples.zip

Example - switching enum in C

enum RainbowColors {Red, Orange, Yellow, Green, Blue, Indigo, Violet};

int main()
{
    switchEnum(Orange);
    return 0;
}

void switchEnum(enum RainbowColors color)
{
    switch(color)
    {
        case Red: printf("Red is the first color in the rainbow."); break;
        case Orange: printf("Orange is the second color in the rainbow."); break;
        case Yellow: printf("Yellow is the third color in the rainbow."); break;
        case Green: printf("Green is the fourth color in the rainbow."); break;
        case Blue: printf("Blue is the fifth color in the rainbow."); break;
        case Indigo: printf("Indigo is the sixth color in the rainbow."); break;
        case Violet: printf("Violet is the seventh color in the rainbow."); break;
        default: printf("I don't know this color.");
    }
    printf("\n");
}

In conclusion, the switch statement is a very convenient tool if we want to check a variable for a set of values. It could significantly reduce the amount of code, compared to multiple if-else and depending on the compiler implementation it could also work faster.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.86 seconds
10,824,602 unique visits