Home > Mobile >  How to check if enum value exists with C preprocessor
How to check if enum value exists with C preprocessor

Time:10-22

I have following problem

Lets assume there is a library that have two versions

Version 1 have declared enum such as this

enum colors {
RED,
GREEN,
BLUE
}

Version 2 looks like this

enum colors {
RED,
GREEN,
BLUE,
TURQUOISE
}

What I would like to do is to perform compile time check with preprocessor as to which enum value I can use, which would look something like this

#include <colors_library.h>

int main()
{

#if TURQUOISE

some_function(TURQUOISE);

#else

some_function(BLUE);

#endif
}

But so far I no success making it work with neither #if and #ifdef directives

CodePudding user response:

It's a good practice to have a version #define in your headers, anyway:

colors_library.h

#define COLOR_VERSION 2
enum colors 
{
    RED,
    GREEN,
    BLUE,
    TURQUOISE
}

Then,

#if COLOR_VERSION == 2
some_function(TURQUOISE);
#else
some_function(BLUE);
#endif

that way, you maintain modern functionality (enums, type-safety, etc...) for everything except the compile-time checks.

CodePudding user response:

Instead of taking the decision with the preprocessor, you could achieve something similar using the library magic_enum. Specifically, you can check for the existence of a value in an enum with magic_enum::enum_contains:

if constexpr (magic_enum::enum_contains<colors>("TURQUOISE")) {
    some_function(*magic_enum::enum_cast<colors>("TURQUOISE"));
}
else {
    some_function(colors::BLUE);
}

CodePudding user response:

Enums and their values are not recognized by the preprocessor. You will have to define some macros. For example:

Version 1:

#define COLORS_TURQUOISE 0

Version 2:

#define COLORS_TURQUOISE 1

So then else where in your code, you can check with:

#if COLORS_TURQUOISE == 1
   // has turquoise
#else
   // does not have turquoise
#endif
  • Related