C Programming Switch Statements

Last modified by Microchip on 2023/11/09 09:07

The switch statement is a more elegant method of handling code that would otherwise require multiple if statements. The only drawback is that the conditions must all evaluate to integer types (int or char) whereas if statements may use any data type in their conditional expressions.

Syntax

switch (expression)
{
case const-expr1: statements1
.
.
.
case const-exprn: statementsn
default: statementsn+1
}

The expression is evaluated and tested for a match with the const-expr in each case clause. The statements in the matching case clause are executed.

switch Statement

Notice that each statement falls through to the next. This is the default behavior of the switch statement. The next flow diagram shows the introduction of break statements. Adding a break statement to each statement block will eliminate fall through, allowing only one case clause's statement block to be executed.

switch break Statements

Back to top

Example 1

1 switch(channel)
2 {
3    case 2:  printf("WBBM Chicago\n"); break;
4    case 3:  printf("DVD Player\n"); break;
5    case 4:  printf("WTMJ Milwaukee\n"); break;
6    case 5:  printf("WMAQ Chicago\n"); break;
7    case 6:  printf("WITI Milwaukee\n"); break;
8    case 7:  printf("WLS Chicago\n"); break;
9    case 9:  printf("WGN Chicago\n"); break;
10    case 10: printf("WMVS Milwaukee\n"); break;
11    case 11: printf("WTTW Chicago\n"); break;
12    case 12: printf("WISN Milwaukee\n"); break;
13    default: printf("No Signal Available\n");
14 }

Back to top

Example 2

1 switch(letter)
2 {
3    case 'a':     
4        printf("Letter 'a' found.\n");
5        break;
6    case 'b':
7        printf("Letter 'b' found.\n");
8        break;
9    case 'c':    
10        printf("Letter 'c' found.\n");
11        break;
12  default:    printf("Letter not in list.\n");
13 }

Notice that the code for each case may be split onto multiple lines and that it doesn't have to start on the line of the case clause itself. Again, spaces, tabs, and newlines are rarely significant in C. Also, notice that now our constant expressions are characters. Remember that the char data type is really just an 8-bit integer, so it is perfectly legal to use here.

Back to top

Example 3

1 switch(channel)
2 {
3    case 4 ... 7:     
4        printf("VHF Station\n"); break;
5    case 9 ... 12:
6        printf("VHF Station\n"); break;
7    case 3: case 8: case 13:     
8        printf("Weak Signal\n"); break;
9    case 14 ... 69:
10        printf("UHF Station\n"); break;
11    default:
12        printf("No Signal Available\n");
13 }

Line 3 is telling us to apply this specific case to channel 4, 5, 6, and 7. Line 7 allows case 3 and 8 to fall through to case 13.

Back to top