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.
The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed.
3) The default statement is optional. Even if the switch case statement do not have a default statement, it would run without any problem.
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, section 6.8.4.2:
[...] If no converted
case
constant expression matches and there is nodefault
label, no part of the switch body is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With