Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a value of an enum member at compile time?

Is it possible to get a value of an enum member at compile time?

In fact, I want to be able to do something like this:

enum { 
   FOO_FIRST = -1,
   FOO_A,
   FOO_B,
   FOO_C,
   FOO_LAST
};

#if FOO_LAST > 10
//...
#else
//..
#endif

I know that the cpp don't know about variables, bad syntax, etc; only things that start with a #(right)? but members of an enum has fixed-size and cannot be changed just like 10 (constant integer) value and the compiler know its size and values. so, Is there no any possibility to do such comparison (as I did above)? Could I use gcc-extensions?

I don't wish to rewrite all my enumerations by using #defines and don't take my time doing some macros change.

like image 748
Jack Avatar asked Nov 02 '12 16:11

Jack


Video Answer


2 Answers

Just use if. Enums can be evaluated at compile time just fine. The compiler will optimize the impossible branches out:

if (FOO_LAST > 10) {
    // A
} else {
    // B
}

The compiler knows which of the two branches (A and B) cannot be reached, so it can eliminate the if completely.

Note however, that you should only use the enumerators directly. For example, in this:

int num = FOO_LAST;
if (num > 10) {
    // A
} else {
    // B
}

GCC will keep the if comparison.

like image 137
Nikos C. Avatar answered Sep 19 '22 04:09

Nikos C.


#ifdef is interpreted by the preprocessor and not by the compiler. The pre-processor does not know anything about the enums's values. So this is not a way to go.

like image 30
alk Avatar answered Sep 19 '22 04:09

alk