2

What does C standard talk about mixing enumerations in the case constants of a switch-case statement? I ensure that there are no duplicate values of the mixed enum types.

switch (value) /* value is int type */
{
case enum1_val: /* enum1_val is of enum type enum1 */
    break;
case enum2_val: /* enum2_val is of enum type enum2 */
    break;
}

I get the code compiled clean with the -ansi -Wall flags, but Klockwork reports some problem in this code.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user1969104
  • 2,340
  • 14
  • 15
  • It's allowed, but what's the point of this kind of enumerations? – Blood Sep 12 '13 at 12:02
  • Because it's harebrained? `value` should have a genuine *type*, and it can only have one type. If you're not sure what *type* a variable has, then you've done something wrong. – Kerrek SB Sep 12 '13 at 12:02
  • 1
    show enum definition in question – Grijesh Chauhan Sep 12 '13 at 12:02
  • As an example of the use case of this construct, the case constants are enumerations defined by different lower layer modules e.g. message id's. The higher layer module handles the messages sent from the lower layer modules using the switch case. – user1969104 Sep 12 '13 at 12:10
  • i think it doesnt matter since they are compile time constants and have type int it should be ok. What does Klockwork say? what are the values of enum1_val and enum2_val? – Koushik Shetty Sep 12 '13 at 12:14
  • Klockwork warns that there is mixed enumeration. – user1969104 Sep 12 '13 at 12:31

1 Answers1

3

It's allowed in C. What you get is a warning by Klocwork because it thinks mixing different enum types is not a good idea. (I personally agree on this):

Quoting from Klocwork:

Inconsistent case labels

The INCONSISTENT.LABEL checker finds situations in which more than one enum type is used as a switch expression or as a label in a switch statement.

Vulnerability and risk

Using labels with different enum types in a switch statement can cause problems because enum members with the same value can have different meanings. The design intent fails, and unexpected results can occur.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294