int a = 10;
switch(a){
case 0:
printf(\"case 0\");
break;
case 1:
printf(\"case 1\");
break;
}
Is the above code valid?
If
yes the above code is valid,
if the switch condition doesn't match any condition of the case and a default is not present the program execution go ahead exiting from the switch without doing anything.
It is perfectly legal code. If a is neither 0 or 1, then the switch block will be entirely skipped.
It's valid not to have a default
case.
However, even if you are sure that you will not have any value rather than 1 and 0, it's a good practice to have a default case, to catch any other value (although it is theoretically impossible, it may appear in some circumstances, like buffer overflow) and print an error.
Default is not mandatory but always good to have it. The code is ideally but our life is not, no harm to put a protection there. It will also help you debugging if any unexpected thing happens.
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.
It's same like no if condition is matched and else is not provided.
default is not an mandatory in switch case. If no cases are matched and default is not provided, just nothing will be executed.