Gaius Parx
Gaius Parx

Reputation: 1075

enum or define, which one should I use?

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

Upvotes: 8

Views: 1362

Answers (6)

Ken A
Ken A

Reputation: 401

#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.

Upvotes: 0

Falmarri
Falmarri

Reputation: 48605

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.

Upvotes: 1

BWW
BWW

Reputation: 515

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.

Upvotes: 1

Puppy
Puppy

Reputation: 147036

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

Upvotes: 11

Computerish
Computerish

Reputation: 9601

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

Upvotes: 2

Kasper
Kasper

Reputation: 2501

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.

Upvotes: 3

Related Questions