Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum or define, which one should I use?

Tags:

objective-c

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
like image 378
Gaius Parx Avatar asked Jun 25 '10 21:06

Gaius Parx


3 Answers

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

like image 124
Puppy Avatar answered Nov 16 '22 01:11

Puppy


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.

like image 36
Kasper Avatar answered Nov 16 '22 00:11

Kasper


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

like image 2
Computerish Avatar answered Nov 15 '22 23:11

Computerish