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 #define
s and don't take my time doing some macros change.
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.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With