错误: case 标签重复
Executing more than one case block in C – is not a syntax error, it’s a logical error and it occurs when you miss to place break statement in the case block.
在C中执行多个case语句不是语法错误,而是逻辑错误,当您错过在break语句中放置break语句时会发生。
In C programming language, it's a feature of the switch case statement, that you can place a single case block for multiple case values, in that case – there is no need to place break in the case block.
在C编程语言中 ,这是switch case语句的功能,在这种情况下 ,您可以为多个case值放置单个case块–无需在case块中放置中断 。
But, if you want to execute one block with one case value, you have to place break statement with each case block.
但是,如果要使用一个case值执行一个块,则必须在每个case块中放置break语句。
Example:
例:
#include <stdio.h>
int main(void) {
int choice = 2;
switch(choice){
case 1:
printf("Case 1\n");
case 2:
printf("Case 2\n");
case 3:
printf("Case 3\n");
case 4:
printf("Case 4\n");
default:
printf("Case default\n");
}
return 0;
}
Output
输出量
Case 2
Case 3
Case 4
Case default
How to fix?
怎么修?
Use break with each case block.
对每个case块使用break 。
Correct code:
正确的代码:
#include <stdio.h>
int main(void) {
int choice = 2;
switch(choice){
case 1:
printf("Case 1\n");
break;
case 2:
printf("Case 2\n");
break;
case 3:
printf("Case 3\n");
break;
case 4:
printf("Case 4\n");
break;
default:
printf("Case default\n");
}
return 0;
}
Output
输出量
Case 2
翻译自: https://www.includehelp.com/c-programs/executing-more-than-one-case-block-error-in-c.aspx
错误: case 标签重复