Question: Question:
From today's real Q & A
I saw the source code where the default
for the switch
was written first. How does it work?
void func(int setting) {
switch (setting) {
default:
case 0:
foo();
break;
case 1:
bar();
break;
case 2:
baz();
break;
}
}
Also, what makes you happy with this description? I feel very uncomfortable (falling from horse)
Answer: Answer:
In C / C ++, default
is "when not all case
match". The order described in the source code does not matter. In the presentation example, if it is other than 0
1
2
, the process shifts to default
. After all
- When 1
bar()
- When it is 2,
baz()
- All other values (including 0)
foo()
What makes me happy is bug countermeasures, or ensuring safety against setting mistakes.
Presentation example It is assumed that setting
is a setting value that comes from outside the program (a value that can be described in a setting file or written in his EEPROM on the board). Therefore, it is assumed that it is possible to predict in advance that a value outside the range will come. And let's assume that 0
is the standard setting operation and 1
2
is the operation within the range where the setting can be changed.
Since the current program does not support anything other than 0
1
2
, it depends on the specifications how to operate for the setting values -1
and 3
, but as the specification, standard operation is performed when it is out of the range. (In an embedded system, it is 100 times better to operate as standard than not to operate at all). When a person who knows such a specification looks at this source code
- Reach
default
when a value outside the set range arrives - The processing is the same as when it is specified
0
, that is,- The source clearly states that
0
is the standard setting - It is clearly stated in the source that the
default
behavior is the same as the default behavior.
- The source clearly states that
- By making it a habit to write
default
first, you can prevent careless mistakes such as forgetting to write.
Is guaranteed semi-automatically. It is undeniable that the description on the source code is slightly unnatural.