Home>Article>Backend Development> What is a switch statement?
The switch statement is a reserved word in some computer languages, and its function is to make judgments and selections in most cases. In C language, switch [switch statement] is often used together with case break default.
#The operating environment of this article: Windows 7 system, Dell G3 computer.
The syntax of the switch statement is as follows (switch, case, break and default are keywords):
switch ( 变量表达式 ) { case 常量1 :语句;break; case 常量2 :语句;break; case 常量3 :语句;break; ... case 常量n:语句;break; default :语句;break; }
When the amount expressed by the variable expression is equal to the constant in one of the case statements When they match, the statements following this case statement are executed, and the statements in all subsequent case statements are executed in sequence, unless thebreak;
statement is encountered and the switch statement is jumped out. If the variable expression does not match the constants of any case statement, the statements in the default statement are executed.
Observe the rules of switch statements
The switch statement is very useful, but it must be used with caution. Any switch statement written must follow the following rules:
Switch can only be used for integral types in basic data types, including int, char, etc. For other types, you must use an if statement.
The parameter type of switch() cannot be real type.
case label must be a constant expression (constantExpression), such as 42 or '4'.
The case tag must be a unique expression; that is, two cases are not allowed to have the same value.
C language switch application example:
Example one:
#includeint main() { double score; printf("请输入分数:\n"); scanf("%lf",&score); switch((int)(score/10)) { case 10: case 9:printf("A(最好)\n");break; case 8:printf("B(优秀)\n");break; case 7:printf("C(良好)\n");break; case 6:printf("D(及格)\n");break; case 5: case 4: case 3: case 2: case 1: case 0:printf("E(不及格)\n");break; default:printf("Error!\n"); } }
Example two:
#includeint main() { char rank; printf("请输入分数等级:(A、B、C、D、E)\n"); scanf("%c",&rank); switch(rank) { case'A':printf("A(90~100)\n");break; case'B':printf("B(80~89)\n");break; case'C':printf("C(70~79)\n");break; case'D':printf("D(60~69)\n");break; case'E':printf("E(0~59)\n");break; default:printf("error!\n");break; } }
[Related learning recommendations:C language tutorial video]
The above is the detailed content of What is a switch statement?. For more information, please follow other related articles on the PHP Chinese website!