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


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.

Christian Bau wrote:
> 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.

I tend to associate version number macros with my enum types, so that
I have a way of checking at compile time that my enums haven't
changed:

    #define Color_VERS   1   // Change this when enum Color changes
    enum Color { ... };

    void hue(enum Color col)
    {
    #if Color_VERS != 1
     #error enum Color has changed
    #endif

        switch (col)
        ...
    }

The #error forces me to re-examine the code that relies on the enum
Color constants.

I also do this sort of thing with structs.

-- David R. Tribble, david@tribble.com, http://www.david.tribble.com --


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