当#define 同样高效时为什么要使用枚举?
所以枚举的工作方式如下:
enum {
false,
true
}
这相当于为什么
int false = 0
int true = 1
我不将 enum
替换为 #define
?
#define FALSE 0
#define TRUE 1
对我来说,它们似乎是可以互换的。我知道 #define
能够处理参数,因此其运行方式与 enum
完全不同。当我们有 #define
在这种情况下时,enum
的主要用途到底是什么?
如果我猜测,由于 #define
是一个预处理器功能,enum
将具有一些运行时优势。我离这还有多远?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您有一长串想要映射为数字的内容并且希望能够在该列表的中间插入一些内容时,
enum
的优点就会显现出来。例如,您有:现在您想将
tangerines
放在oranges
之后。使用#define
,您必须重新定义葡萄
、桃子
和杏
的数量。使用枚举,它会自动发生。是的,这是一个人为的示例,但希望它能给您带来启发。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:Now you want to put
tangerines
afteroranges
. With#define
s, you'd have to redefine the numbers ofgrapes
,peaches
, andapricots
. Using enum, it would happen automatically. Yes, this is a contrived example, but hopefully it gives you the idea.我发现它对于在 gdb 等环境中进行调试很有用,因为枚举值是在编译时处理的(其中 #define 是预处理器宏),因此可用于内省。
I find it useful for debugging in an environment such as gdb since enum values are handled at compile time (where #define is a preprocessor macro) and thus available for introspection.
尽管您的问题被标记为 C,但用 C++ 编写时有一个很大的优势,您可以将
enum:s
放在类或命名空间内。这样你就可以引用像
SpaceshipClass::galaxy
这样的常量。Although your question is tagged as C, there is a big advantage when writing in C++, you can place
enum:s
inside classes or namespaces.This way you could refer to your constants like
SpaceshipClass::galaxy
.enum 是一个整数常量。因此,在编译过程中会进行类型检查。
enum is an integer constant. so, there would be a type check during compilation process.