This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Missing default in switch


In article <380DE980.20A6F404@tribble.com>, David R Tribble
<david@tribble.com> wrote:

> Alex Vinokur wrote:
> > Is there any possibility to make a compiler protest
> > against missing default-word in switch-statement?
> 
> Some do, but none are required to by the ISO standard.
> 
> Sometimes it's irritating when they do issue a warning, though.
> For example:
> 
>     enum Color { RED, BLUE, GREEN };
> 
>     void hue(enum Color col)
>     {
>         switch (col)
>         {
>         case RED:
>             ...do something...
> 
>         case BLUE:
>             ...do something...
> 
>         case GREEN:
>             ...do something...
> 
>         /* No default necessary, i.e., do nothing */
>         }
>     }
> 
> Some compilers (and some lint programs) allow you to add a special
> comment where the missing default goes to indicate that the default
> case is omitted on purpose.

I have seen one compiler that would check if (1) the value used by the
switch statement was an enum, like in your example, and (2) you had cases
for most, but not all, defined values of the enum, and give a warning in
that case. ("Most but not all" was defined something like more than 70% of
the enum values). 

Your code would give no warning. If you added "YELLOW" to your enum
without changing the switch statement, you would get a warning. If you
added threehundred more colors to the enum, the warning goes away. 

This is better IMO than a special comment saying that default is not
required, because that comment would be correct with your code example
today, but would be wrong when the enum is changed.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]