Last Updated on
Switch statement is a substitute for long if statements that compare a variable to several “integral” values (“integral” values are simply values that can be expressed as an integer, such as the value of a char). The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. C switch statement is a multiway decisions that tests whether a variable or expression matches one of a number of constant integer values, and branches accordingly.
Syntax of switch statement:
case constant-expression :
case constant-expression :
// you can have any number of case statements.
default : //Optional
The condition of a switch statement is a value.. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from falling through and executing the code in all the other case statements. An important thing to note about the switch statement is that the case values may only be constant integral expressions.
The default case is optional, but it is wise to include it as it handles any unexpected cases. Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user.
Some of the points to keep in mind while using switch statement are :
- In C 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 compiler will issue an error message.
- The case constant expression must be a constant integer value.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. Although as mentioned the break statement is not mandatory but it is sound to use this break statement.
- The defaut statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.
Program to illustrate use of switch statement:
case 100 :
printf( "Excellent\n" );
case 90 :
printf( "Very Good\n" );
case 80 :
printf( "Good" );
printf( "Work hard\n" );
Output will be:
- MongoDB Operators Tutorial – What are Different Operators Available? - October 5, 2019
- MongoDB Projection Tutorial : Return Specific Fields From Query - March 9, 2019
- MongoDB Index Tutorial – Create Index & MongoDB Index Types - July 6, 2018