问题描述
我对何时使用宏或枚举感到困惑.两者都可以用作常量,但是它们之间有什么区别,并且两者的优点是什么?它是否与编译器级别有关?
I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it somehow related to compiler level or not?
推荐答案
就可读性而言,枚举是比宏更好的常量,因为相关的值被组合在一起.此外,enum
定义了一个新类型,因此您程序的读者可以更轻松地找出可以传递给相应参数的内容.
In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, enum
defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter.
比较
#define UNKNOWN 0
#define SUNDAY 1
#define MONDAY 2
#define TUESDAY 3
...
#define SATURDAY 7
到
typedef enum {
UNKNOWN,
SUNDAY,
MONDAY,
TUESDAY,
...
SATURDAY,
} Weekday;
这样的代码更容易阅读
void calendar_set_weekday(Weekday wd);
比这个
void calendar_set_weekday(int wd);
因为您知道可以传递哪些常量.
because you know which constants it is OK to pass.
这篇关于什么使 C、宏或枚举中的常量更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!