What if I don't write default in switch case?
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.
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.
int a=10;
switch(a)
{
case 0: printf("case 0");
break;
case 1: printf("case 1");
break;
default: // do nothing;
break;
}
The code generated with / without the default
should be identical.
It is perfectly legal code. If a is neither 0 or 1, then the switch block will be entirely skipped.