2.9.1. switch Statements:
The C switch
statement can be used in place of some, but not all, chaining
if
-else if
code sequences. While switch
doesn’t provide any additional
expressive power to the C programming language, it often yields more concise
code branching sequences. It may also allow the compiler to produce branching
code that executes more efficiently than equivalent chaining if
-else if
code.
The C syntax for a switch
statement looks like:
switch (<expression>) {
case <literal value 1>:
<statements>;
break; // breaks out of switch statement body
case <literal value 2>:
<statements>;
break; // breaks out of switch statement body
...
default: // default label is optional
<statements>;
}
A switch statement is executed as follows:
-
The
expression
evaluates first. -
Next, the
switch
searches for acase
literal value that matches the value of the expression. -
Upon finding a matching
case
literal, it begins executing the statements that immediately follow it. -
If no matching
case
is found, it will begin executing the statements in thedefault
label if one is present. -
Otherwise, no statements in the body of the
switch
statement get executed.
A few rules about switch
statements:
-
The value associated with each
case
must be a literal value — it cannot be an expression. The original expression gets matched for equality only with the literal values associated with eachcase
. -
Reaching a
break
statement stops the execution of all remaining statements inside the body of theswitch
statement. That is,break
breaks out of the body of theswitch
statement and continues execution with the next statement after the entireswitch
block. -
The
case
statement with a matching value marks the starting point into the sequence of C statements that will be executed — execution jumps to a location inside theswitch
body to start executing code. Thus, if there is nobreak
statement at the end of a particularcase
, then the statements under the subsequentcase
statements execute in order until either abreak
statement is executed or the end of the body of theswitch
statement is reached. -
The
default
label is optional. If present, it must be at the end.
Here’s an example program with a switch
statement:
#include <stdio.h>
int main() {
int num, new_num = 0;
printf("enter a number between 6 and 9: ");
scanf("%d", &num);
switch(num) {
case 6:
new_num = num + 1;
break;
case 7:
new_num = num;
break;
case 8:
new_num = num - 1;
break;
case 9:
new_num = num + 2;
break;
default:
printf("Hey, %d is not between 6 and 9\n", num);
}
printf("num %d new_num %d\n", num, new_num);
return 0;
}
Here are some example runs of this code:
./a.out enter a number between 6 and 9: 9 num 9 new_num 11 ./a.out enter a number between 6 and 9: 6 num 6 new_num 7 ./a.out enter a number between 6 and 9: 12 Hey, 12 is not between 6 and 9 num 12 new_num 0