![]() |
question about macro and enum
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 ?? |
Re: question about macro and enum
On 10/11/2011 03:40 AM, gaoqiang wrote:
> 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. -- James Kuyper |
Re: question about macro and enum
China Blue Corn Chips <chine.bleu@yahoo.com> writes:
> In article <142687ac-a15c-4153-96ae-3a1f7d243474@c14g2000prn.googlegroups.com>, > gaoqiang <gaoqiangscut@gmail.com> wrote: >> 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 ?? > > #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. -- Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst> "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" |
| All times are GMT. The time now is 03:36 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.