enum and #define appears to be able to do the same thing, for the example below defining a style. Understand that #define is macro substitutio开发者_高级运维n for compiler preprocessor. Is there any circumstances one is preferred over the other?
typedef enum {
SelectionStyleNone,
SelectionStyleBlue,
SelectionStyleRed
} SelectionStyle;
vs
#define SELECTION_STYLE_NONE 0
#define SELECTION_STYLE_BLUE 1
#define SELECTION_STYLE_RED 2
Don't ever use defines unless you MUST have functionality of the preprocessor. For something as simple as an integral enumeration, use an enum.
An enum is the best if you want type safety. They are also exported as symbols, so some debuggers can display them inline while they can't for defines.
The main problem with enums of course is that they can only contain integers. For strings, floats etc... you might be better of with a const or a define.
The short answer is that it probably doesn't matter a lot. This article provides a pretty good long answer:
http://www.embedded.com/columns/programmingpointers/9900402?_requestid=345959
When there's a built-in language feature supporting what you want to do (in this case, enumerating items), you should probably use that feature.
Defines are probably slightly faster (at runtime) than enums, but the benefit is probably only a handful of cycles, so it's negligible unless you're doing something that really requires that. I'd go with enum, since using the preprocessor is harder to debug.
#define DEFINED_VALUE 1
#define DEFINED_VALUE 2 // Warning
enum { ENUM_VALUE = 1 };
enum { ENUM_VALUE = 2 }; // Error
With #define, there is a higher probability of introducing subtle bugs.
精彩评论