Just a sample of the Echomail archive
COMPLANC:
[ << oldest | < older | list | newer > | newest >> ]
|  Message 241,399 of 243,097  |
|  Janis Papanagnou to Richard Harnden  |
|  Re: bugprone-switch-missing-default-case  |
|  22 Oct 25 15:56:45  |
 
From: janis_papanagnou+ng@hotmail.com
On 22.10.2025 13:44, Richard Harnden wrote:
> On 22/10/2025 10:32, Janis Papanagnou wrote:
>> On 22.10.2025 10:56, pozz wrote:
>>>
>>>> Switch statements without a default case can lead to unexpected
>>>> behavior and incomplete handling of all possible cases. When a switch
>>>> statement lacks a default case, if a value is encountered that does
>>>> not match any of the specified cases, the program will continue
>>>> execution without any defined behavior or handling.
>>>
>>> Maybe I misunderstood that sentence caused by my bad English. I knew
>>> that in case the switch value is not present in any case inside the
>>> switch, the program continues without doing anything (in the switch) and
>>> without any problem.
>>>
>>> int x = 3;
>>> switch(x) {
>>> case 1: printf("Hello");break;
>>> case 2: printf("World");break;
>>> }
>>>
>>> Will the program execution continue without any defined behaviour?
>>
>> Your program fragment is well defined.
>>
>> What the poster certainly tried to express was that in case you
>> haven't implemented a complete list of all possible cases and
>> also not provided a 'default' to catch all non-specified cases,
>> then you might get in troubles with your program, probably by
>> possible oversights, future extensions, new data, and whatnot.
>>
>> Personally I have the habit to always define a default branch,
>> and even if that default is impossible to reach you'll find an
>> error message (like "internal error with unexpected value...")
>> generated at that place.
>>
> Use an enum, and the compiler will warn you ...
Maybe. Although I don't recall that the "C"-compilers I formerly
used checked enums as you've shown below. - But anyway...
Enums don't help if you use and compare against (for example)
characters that are (for example) got from an external source.
char * cmds = "CMDQ"; // 'D' maybe added later
char cmd;
...some n lines of code...
...get input cmd...
...optionally verify cmd with cmds...
...some more m lines of code...
switch (cmd) {
case 'C': ...;
case 'M': ...;
default: printf ("Error: uncaught cmd '%c'\n", cmd);
}
It's good to take precautions and define the 'default' case. YMMV.
Janis
>
> $ cat x.c
> #include
|
[ << oldest | < older | list | newer > | newest >> ]
(c) 1994, bbs@darkrealms.ca