如果我不在 switch case 中写 default 怎么办? [英] What if I don't write default in switch case?

查看:76
本文介绍了如果我不在 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 吗?

If I am sure that int a will not have any other value than 1 and 0, can I avoid default?

如果在任何情况下一个值将不同于 1 和 0 怎么办?

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.

推荐答案

代码有效.如果没有 default: 标签并且没有一个 case 标签与switched"值匹配,则不会执行任何受控复合语句.会从 switch 语句的末尾继续执行.

The code is valid. If there is no default: label and none of the case 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,第 6.8.4.2 节:

ISO/IEC 9899:1999, section 6.8.4.2:

[...] 如果没有转换的 case 常量表达式匹配并且没有 default 标签,则不会执行 switch 体的任何部分.

[...] If no converted case constant expression matches and there is no default label, no part of the switch body is executed.

这篇关于如果我不在 switch case 中写 default 怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆