Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I don't write default in switch case?

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.

like image 338
Jeegar Patel Avatar asked Nov 05 '11 15:11

Jeegar Patel


People also ask

What happens if there is no default in switch case?

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.

Is default optional in switch case?

3) The default statement is optional. Even if the switch case statement do not have a default statement, it would run without any problem.


1 Answers

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 no default label, no part of the switch body is executed.

like image 151
CB Bailey Avatar answered Oct 02 '22 00:10

CB Bailey