In practice we often wish to choose different patterns of behaviour, according to any of several possible values of an expression. The C construction which allows this is called the switch statement. The useful form of this is:
switch ( expression ) { (case const-value: statement-list break; )* default: statement-list break; }where the expression is of a discrete type and const-value is a constant integer value.
When a program executes a switch statement, the value of its expression is first determined. If this matches any of the constant values in a case, the statements following that label are executed. If the value does not match any of the case labels, the default label is chosen.
Note that statements between that selected and the switchÕs terminating } are only skipped if there is a break statement following. If you forget the break;, the next branch of the switch will also be executed. Although the default label is optional, it is often wise to include it to catch unexpected behaviour in your program. If no matching constant value is found as a case label and no default is given, the whole switch is skipped.
#include <stdio.h> /* Pocket calculator example using case statement */ void main() { float Result, Value; char Operator; scanf("%f",&Result); while ((Operator=getchar()) != '=') { scanf("%f",&Value); switch (Operator) { case '+': Result = Result + Value; break; case '-': Result = Result - Value; break; case '*': Result = Result * Value; break; case '/': Result = Result / Value; break; } } printf("%f\n",Result); }This switch statement is exactly equivalent to
if (Operator == '+') Result = Result + Value; else if (Operator == '-') Result = result - Value; else if (Operator == '*') Result = Result * Value; else if (Operator == '/') Result = Result / Value;Plain text to compile.