C compiler checking for overlap in multiple enum

Viewed 146

Does anyone knows if it is possible to get the compiler to check if two enums overlap?

We have several SW packages, were each has an enum with eeprom address definitions Is there a way to get the compiler to combine these and check for overlaps?

typedef enum
{
    DEF_A = 1,
    DEF_B = 2
} Enum1;

typedef enum
{
    DEF_C = 1,
    DEF_D = 3
} Enum2;

enum 
{
    Enum1, 
    Enum2
};

=> Generate compile error since DEF_1 and DEF_3 has the same value

2 Answers

Does anyone know if it is possible to get the compiler to check if two enums overlap?

Yes, I know, and no, it is not possible. For the same reason you won't find a compiler warning about two different integers being assigned 0: it's perfectly okay.

You should understand that each enumeration list is nothing but a mapping of identifiers to values. Different identifiers are allowed to map to the same value, even in the same enumeration list:

enum count { ZIP = 0, ZILCH = 0, NADA = 0, ZERO = 0, ONE, TWO, THREE };

is not a problem. If you want to avoid identifiers with the same value, what you can do is place them all in the same enum list and do not assign any of them, or maximally the first.

If you need to check this across more than one enum list, you need to look for solutions outside the C language.

With a good compiler such as gcc (-Woverride-init), you may be able to create a "super array" including all known enumeration constants in the project in the form of designated initializers:

const int dummy[] = 
{
  [DEF_A] = 0,
  [DEF_B] = 0,
  [DEF_C] = 0,
  [DEF_D] = 0,
};

The gcc compiler will now poke you in case of duplicates:

x|warning: initialized field overwritten [-Woverride-init]|
x|warning: (near initialization for 'dummy[1]') [-Woverride-init]|

where x is the line number where the value dummy[1] was encountered for the second time (the [DEF_C] line).

Related