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:
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
Please enter an integer to choose a color(red=1,green=2,blue=3):
2
u chose green color
y
o
0 comments:
Post a Comment