I'm coming back to some C development after working in C++ for a while. I've gotten it into my head that macros should be avoided when not necessary in favor of making the compiler do more work for you at compile-time. So, for constant values, in C++ I would use static const variables, or C++11 enum classes for the nice scoping. In C, static constants are not really compile-time constants, and enums may (? or may not?) behave slightly differently.
So, is it reasonable to prefer using enums for constants rather than #defines?
For reference, here's an excellent list of pros and cons of enums, #defines and static consts in C++.
Why to use enum 1 enums are implicitly final subclasses of java.lang.Enum 2 if an enum is a member of a class, it's implicitly static 3 new can never be used with an enum, even within the enum type itself 4 name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired More items...
All enum classes inherit the Java standard class java.lang.Enum from which they inherit some potentially useful methods. The inherited methods you should know about are name (), ordinal (), and static method values (). The name () method returns the name exactly as defined in the enum value.
Because it can store only two values, two specific values. So Enum can be thought of as having the same type of facilities where a user will define how many and what type of value it will store, just in a slightly different way. :)
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
The advantage of using enum { FOO=34 };
over #define FOO 34
is that macros are preprocessed, so in principle the compiler don't really see them (in practice, the compiler does see them; recent GCC has a sophisticated infrastructure to give from what macro expansion some internal abstract syntax tree is coming).
In particular, the debugger is much more likely to know about FOO
from enum { FOO=34 };
than from #define FOO 34
(but again, this is not always true in practice; sometimes, the debugger is clever enough to be able to expand macros...).
Because of that, I prefer enum { FOO=34 };
over #define FOO 34
And there is also a typing advantage. I could get more warnings from the compiler using enum color_en { WHITE, BLACK }; enum color_en color;
than using bool isblack;
BTW, static const int FOO=37;
is usually known by the debugger but the compiler might optimize it (so that no memory location is used for it; it might be just an immediate operand inside some instruction in the machine code).
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