We can define some magic number with #define:
#define OPERATION_1 0x00000001
#define OPERATION_2 0x00000002
#define OPERATION_3 0x00000003
...
We can also do that with enum:
enum OPERATION
{
OPERATION_1=0x00000001,
OPERATION_2=0x00000002,
OPERATION_3=0x00000003,
...
};
What make you prefer preprocessor? What make you prefer enum? Any
experience support that?
What I say: Enums are the way to go. They give you all the benefits
of a compile-time constant, plus the benefits of the language's type
checking.
What I do: #define, #define, #define. Why? Because #defines are
easier to type. They don't require you to insert = signs everywhere,
or to count commas. (Yes, you just need to stick a comma after each
enumeration value --- but that's still a lot of extra typing, even if
it is mindless.)
There's another dumb reason I use #defines over enums: I don't have
to think about capitalization. #defined constants in C code are ALL_CAPS,
always. Enumeration constants... well, I'd have to think about that.
I'd probably lower_case enum values in most cases. But the important
thing is, I'd have to think about it. With #defines, there's a default
style that everyone knows by heart, so it's one less thing to worry
about.
Another dumb reason: Enum definitions define a new "type." Which I
usually feel deserves a name, such as
enum suit {
Hearts, Spades, Clubs, Diamonds,
};
Now, suppose I write a function that takes a suit as a parameter. Do
I write
void pick_a_card(suit s);
or do I write
void pick_a_card(int s);
? With #defines, there's no decision to make. No new type, no tricky
style decisions.
So there you have it --- I recommend 'enum' in theory, but when it
comes to actual coding (of relatively tiny stuff, I must add), I almost
always use '#define' instead, because it means fewer time-consuming
style decisions for me.
HTH, but get a second opinion,
-Arthur