question about macro and enum

G

gaoqiang

recently, I came into some code like this:

#define ABCD_A 0x01
#define ABCD_B 0x02
#define ABCD_C 0x04

but someelse, there's code like that:

enum{
EFGH_E=0x01,
EFGH_F=0x02,
EFGH_G=0x04,
};

then,when will I use macro, and when enum ??
 
J

James Kuyper

recently, I came into some code like this:

#define ABCD_A 0x01
#define ABCD_B 0x02
#define ABCD_C 0x04

but someelse, there's code like that:

enum{
EFGH_E=0x01,
EFGH_F=0x02,
EFGH_G=0x04,
};

then,when will I use macro, and when enum ??

A good rule of thumb, violated by the ABCD_* macros above, is that a
closely related series of int constants should be packed together as
enumeration constants of a single enumerated type, while unrelated
constants and constants that cannot be of type int should be defined as
macros. However, there's nothing particularly wrong with violating that
rule of thumb, it's mainly a matter of personal preference. Like all
rules of thumb, there can be reasonable exceptions. For instance, use of
a macro allows user code to check

#ifdef ABCD_B

there's no comparable way of checking whether a given enumeration
constant exists without generating a syntax error when it is not.
 
K

Keith Thompson

China Blue Corn Chips said:
#defines have been with us since the beginning, but enums were a subsequent
feature. So some people and some code still use #defines when enums would be
better.

Enums have the drawback that the values can only be of type int.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top