About C 'switch' statement
In C programming, the switch statement is a control flow statement that is used to perform different actions based on different conditions.
It is used to test the equality of a variable against a list of conditions using case keyword. When it finds equality with a condition, the block of code under the case label condition is executed.
The switch statement is an organized alternative of writing many if..else statements. It provides a more readable and efficient way to handle multiple conditions.
Syntax of 'switch' statement
-
switch: Theswitchkeyword begins theswitchstatement. -
expression: The expression is a variable that is evaluated once and compared with each 'case' constant. -
case constant1: case constant2:: Eachcasekeyword is followed by a constant value and a colon ':'. The block of code under case statement is executed when the expression matches the constant. Aswitchstatement can have as manycasestatements as required. -
break: Thebreakstatement terminates thecaseas well asswitchstatement and gets the control out of theswitchstatement. -
default:: Thedefaultcase runs if no case constants match the expression. It is optional.
Create a 'switch' statement
A 'switch' statement has been created in the following example:
Example of 'switch' statement
Output of the above example
Excellent! your grade is A.
Explanation of code:
-
int marks = 90;: The line initializes an integer variable 'marks' with value 90. It will be used as expression in the 'switch' statement. -
switch (marks): The 'switch' keyword begins the 'switch' statement with 'marks' expression. It tests the value of 'marks' and transfers control to the corresponding case label. -
case 70:: If 'marks' is equal to 70, the code block under the case label'printf("Well done, your grade is B.\n");'will be executed and the 'break;' statement will get the control out of the 'switch' block. -
case 90:: If 'marks' is equal to 90, the code block under the case label'printf("Excellent! your grade is A.\n");'will be executed and the 'break;' statement will get the control out of the 'switch' block. As the expression value is equal to the case value, the code block under this case will be executed. -
default:: If 'marks' does not match any of the specified case values, the code block under the default label'printf("Invalid marks\n");'will be executed.