8

enum and #define appears to be able to do the same thing, for the example below defining a style. Understand that #define is macro substitution 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
Gaius Parx
  • 1,065
  • 1
  • 11
  • 18
  • See also: [Should I use #define, enum or const?](http://stackoverflow.com/questions/112433/should-i-use-define-enum-or-const) – Shog9 Jun 25 '10 at 22:48

6 Answers6

11

Don't ever use defines unless you MUST have functionality of the preprocessor. For something as simple as an integral enumeration, use an enum.

Puppy
  • 144,682
  • 38
  • 256
  • 465
3

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.

Kasper
  • 2,451
  • 2
  • 17
  • 19
  • what do you mean about type safety? this code is legal: enum E { A = 1 }; E t = E(2); and the result is undefined. So enums are TYPE safe, but not VALUE safe, so they are almost bad as defines/ – f0b0s Jun 25 '10 at 22:21
  • With casts you can do everything, that doesn't prove a thing. – Kasper Jun 26 '10 at 16:39
2

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

Computerish
  • 9,590
  • 7
  • 38
  • 49
1

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.

Thromordyn
  • 1,581
  • 4
  • 17
  • 45
Falmarri
  • 47,727
  • 41
  • 151
  • 191
1

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.

BWW
  • 517
  • 4
  • 11
0
#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.

Ken A
  • 371
  • 2
  • 4