如果我不在 switch case 中写入 default 会怎样?
int a = 10;
switch(a){
case 0:
printf("case 0");
break;
case 1:
printf("case 1");
break;
}
上述代码有效吗?
如果我确定 int a
除了 1 和 0 之外不会有任何其他值,我可以避免使用 default
吗?
如果在任何情况下值都不同于 1 和 0 该怎么办?
我知道这是一个愚蠢的问题,但我想这可能是非法或未定义的行为,所以我只是要求确认一下。
int a = 10;
switch(a){
case 0:
printf("case 0");
break;
case 1:
printf("case 1");
break;
}
Is the above code valid?
If I am sure that int a
will not have any other value than 1 and 0, can I avoid default
?
What if in any case a value will be different from 1 and 0?
I know this is a silly question but I was thinking that perhaps it would be illegal or undefined behavior soI just asked to make sure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
该代码有效。如果没有
default:
标签并且没有一个case
标签与“switched”值匹配,则不会执行任何受控复合语句。将从 switch 语句末尾继续执行。ISO/IEC 9899:1999,第 6.8.4.2 节:
The code is valid. If there is no
default:
label and none of thecase
labels match the "switched" value, then none of the controlled compound statement will be executed. Execution will continue from the end of the switch statement.ISO/IEC 9899:1999, section 6.8.4.2:
正如其他人指出的那样,这是完全有效的代码。然而,从编码风格的角度来看,我更喜欢添加一个空的
default
语句和注释,以表明我没有无意中忘记它。使用 / 不使用
default
生成的代码应该是相同的。As others have pointed out it is perfectly valid code. However, from a coding style perspective I prefer adding an empty
default
statement with a comment to make clear that I didn't unintentionally forget about it.The code generated with / without the
default
should be identical.这是完全合法的代码。如果 a 既不是 0 也不是 1,那么 switch 块将被完全跳过。
It is perfectly legal code. If a is neither 0 or 1, then the switch block will be entirely skipped.
没有
default
情况是有效的。但是,即使您确定不会有除 1 和 0 之外的任何值,使用默认情况来捕获任何其他值也是一个很好的做法(尽管理论上不可能,但在某些情况下可能会出现,例如缓冲区溢出)并打印错误。
It's valid not to have a
default
case.However, even if you are sure that you will not have any value rather than 1 and 0, it's a good practice to have a default case, to catch any other value (although it is theoretically impossible, it may appear in some circumstances, like buffer overflow) and print an error.
是的,上面的代码是有效的。
如果 switch 条件与 case 的任何条件都不匹配并且默认值不存在,则程序将继续执行,从 switch 退出而不执行任何操作。
Yes, the above code is valid.
If the switch condition doesn't match any condition of the case and a default is not present, the program execution goes ahead, exiting from the switch without doing anything.
默认值不是强制性的,但拥有它总是好的。
代码是理想的,但我们的生活却并非如此,在那里设置保护也没有任何害处。如果发生任何意外情况,它还可以帮助您进行调试。
Default is not mandatory, but it always good to have it.
The code is ideally, but our life is not, and there isn't any harm in putting in a protection there. It will also help you debugging if any unexpected thing happens.
这与 no if 条件匹配但未提供 else 相同。
default 在 switch 情况下不是强制的。如果没有匹配任何情况并且未提供默认值,则不会执行任何操作。
It's same like no if condition is matched and else is not provided.
default is not an mandatory in switch case. If no cases are matched and default is not provided, just nothing will be executed.