如果我不在 switch 情况下编写 default 怎么办?

int a = 10;
switch(a){
case 0:
printf("case 0");
break;
case 1:
printf("case 1");
break;
}

以上代码有效吗?

如果我确定 int a的值除了1和0之外没有其他值,那么我可以避免使用 default吗?

如果在任何情况下,一个值将不同于1和0,该怎么办?

我知道这是一个愚蠢的问题,但我在想,也许这是非法的或未定义行为的,所以我只是要求确认一下。

109397 次浏览

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.

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.

It is perfectly legal code. If a is neither 0 or 1, then the switch block will be entirely skipped.

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 goes ahead, exiting from the switch without doing anything.

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'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.

Default is not mandatory, but it always good to have it.

The code is ideally, but our life is not, and there isn't any harm in putting in a protection there. It will also help you debugging if any unexpected thing happens.

The syntax for a switch statement in C programming language is as follows:

switch(expression) {


case constant-expression  :
statement(s);
break; /* optional */


case constant-expression  :
statement(s);
break; /* optional */


/* you can have any number of case statements */
default : /* Optional */
statement(s);
}