The
#switch statement allows testing of a variable for equality with a list of values. Each value is called a case, and the variable being opened is checked against each switch case.
The syntax of switch statement in C programming language is as follows- p>
switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }
The following rules apply to switch statement-
switch The expression statement used must have an integral or enumeration type, or be a class type where the class has a single conversion function to an integral or enumeration type.
You can have any number switch in the case statement. Each case is followed by the value to be compared and a colon.
The constant expression of the instance must be of the same data type as the variable in switch, which must be a constant or a literal.
When the variable being switched is equal to a case, the statements following the case will be executed until the break statement is reached.
When the break statement is reached, the switch terminates and the flow of control jumps to the next line after the switch statement.
Not every case needs to contain break. If no interrupt occurs, control flow will proceed to subsequent situations until an interrupt is reached.
The switch statement can have an optional < strong>default case, which must appear at the end of the switch. A default case can be used to perform a task when all else fails. Interrupts are not required by default.
Real-time demonstration
#include <stdio.h> int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!</p><p>" ); break; case 'B' : case 'C' : printf("Well done</p><p>" ); break; case 'D' : printf("You passed</p><p>" ); break; case 'F' : printf("Better try again</p><p>" ); break; default : printf("Invalid grade</p><p>" ); } printf("Your grade is %c</p><p>", grade ); return 0; }
Well done Your grade is B
The above is the detailed content of switch case statement in C language. For more information, please follow other related articles on the PHP Chinese website!