为什么我的使用逻辑表达式作为案例标签的代码会引发错误? [英] Why my code which uses a logical expression as a case label throws error?
问题描述
switch(at){
case (at>0 && at<5) :
printf("Average Time Taken (Hrs)\n%d.0",at);
printf("Your Salary is Rs.%d",pj*1500 + 5000);
break;
其余代码类似.我在这个 case (at>0 && at<5) 中遇到错误:
rest of the codes are similar. And i'm getting error for this case (at>0 && at<5) :
推荐答案
恐怕这是不可能的.引用 C11
,章节 §6.8.4.2
I'm afraid this is not possible. Quoting C11
, chapter §6.8.4.2
每个case
标签的表达式应该是一个整数常量表达式,并且不能有两个同一 switch
语句中的 case 常量表达式应具有相同的值转换后.[....]
The expression of each
case
label shall be an integer constant expression and no two of the case constant expressions in the sameswitch
statement shall have the same value after conversion. [....]
所以 case
标签表达式不能依赖于运行时生成的值.
so the case
label expression cannot be a runtime-generated value dependent.
你可以,使用fall-through语法来实现你想要的,比如
You can, use a fall-through syntax to achieve what you want, something like
switch(at){
case 1:
case 2:
case 3:
case 4:
printf("Average Time Taken (Hrs)\n%d.0",at);
printf("Your Salary is Rs.%d",pj*1500 + 5000);
break;
//some other case
否则,如果您可以使用 gcc
扩展名,则可以使用 case-range 语法,类似
Otherwise, if you're ok with using gcc
extension, you can use case-range syntax, something like
switch(at){
case 1 ... 4:
printf("Average Time Taken (Hrs)\n%d.0",at);
printf("Your Salary is Rs.%d",pj*1500 + 5000);
break;
这篇关于为什么我的使用逻辑表达式作为案例标签的代码会引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!