C Switch Statement

The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Here are the common switch statement syntax:

switch(expression){
case value1: /* execute unit of code 1 */
break;
case value2: /* execute unit of code 2 */
break;
...
default: /* execute default action */
break;
}

In the switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value which is returned by expression must be an integer value otherwise the statement will not compile.
The case constant expression must be an integer value and all values in case statement are equal.
When a break statement is executed, it causes execution to continue with the statement following the closing brace for the switch. The break statment is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logics happen.
The default statement is the default choice of the switch statement if all cases statement are not satisfy with the expression. The break after the default statements is not necessary unless you put another case statement below it.
Here is an example of using C switch statement

#include <stdio.h>

const int RED = 1;
const int GREEN = 2;
const int BLUE = 3;

void main(){
int color = 1;
printf("Enter an integer to choose a color(red=1,green=2,blue=3):\n");
scanf("%d",&color);

switch(color){
case RED: printf("you chose red color\n");
break;
case GREEN:printf("you chose green color\n");
break;
case BLUE:printf("you chose blue color\n");
break;
default:printf("you did not choose any color\n");
}
}

Here is the output:
Please enter an integer to choose a color(red=1,green=2,blue=3):
2
you chose green color

source:http://cprogramminglanguage.net/c-switch-statement.aspx

No comments:

Post a Comment