Case without default label
I'm a big fan of skipping the "default:" label in a enum-switch-case. So I get compiler warnings, when the enum has a new value which is not handled by the switch-case.
Now a colleague stated, that when passing an integer to this switch-case which is not covered by the enumeration I will get a segmentation fault.
At least the gcc we re using handles it correctly. Also the Visual Studio documentation says: If "none of the constants match the constants in the case labels and default label is not present >>> Control is transferred to the statement after the switch statement."
Is this the standard and thus the behaviour of all (or at least the most) compilers?
The MS compiler seems to do it right. Here's what the standard says (6.4.2/5):
If no case constant matches the condition, and if there is a default
label, control passes to the statement labeled by the default
label. If no case matches and if there is no default
then none of the statements in the switch is executed.
It can cause a segmentation fault only if skipped case breaks your code. Otherwise no compiler should emit code that will generate a segmentation fault.
Example that will generate a fault:
switch(flag) {
case Type1: p = malloc(200); break;
case Type2: p = malloc(100); break;
}
memcpy(p, source, 10);
[stmt.switch] states:
If no case matches and if there is no default then none of the statements in the switch is executed.
So yes, VS follows the standard in this regard.
链接地址: http://www.djcxy.com/p/84434.html上一篇: 开关case语句错误:case表达式必须是常量表达式
下一篇: 没有默认标签的情况