问题描述
所以枚举是这样工作的:
enum {错误的,真的}
相当于
int false = 0整数真 = 1
为什么我不将 enum
替换为 #define
?
#define FALSE 0#define TRUE 1
对我来说,它们似乎可以互换.我知道 #define
能够处理参数,因此其操作方式与 enum
完全不同.当我们有 #define
在这种情况下时,enum
的主要用途究竟是什么?
如果我猜的话,由于 #define
是一个预处理器特性,enum
将具有一些运行时优势.我离我有多远?
提前致谢.
enum
的优势在您有一长串想要映射为数字的事物并且想要成为能够在该列表的中间插入一些东西.例如,您有:
现在你想把 tangerines
放在 oranges
之后.使用#define
s,您必须重新定义grapes
、peaches
和apricots
的数量.使用枚举,它会自动发生.是的,这是一个人为的例子,但希望它能给你一个想法.
So an enum works like this:
enum {
false,
true
}
which is equivalent to
int false = 0
int true = 1
Why wouldn't I substitute enum
with #define
?
#define FALSE 0
#define TRUE 1
To me, it seems like they are interchangeable. I'm aware that #define
is able to handle arguments, hence operates in an entirely different way than enum
. What exactly are the main uses of enum
when we have #define
in this case?
If I were to guess, as the #define
is a preprocessor feature, enum
would have some runtime advantages. How far off am I?
Thanks in advance.
The advantages of enum
show up when you have a long list of things you want to map into numbers, and you want to be able to insert something in the middle of that list. For example, you have:
pears 0 apples 1 oranges 2 grapes 3 peaches 4 apricots 5
Now you want to put tangerines
after oranges
. With #define
s, you'd have to redefine the numbers of grapes
, peaches
, and apricots
. Using enum, it would happen automatically. Yes, this is a contrived example, but hopefully it gives you the idea.
这篇关于为什么在#define 同样有效时使用枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!