为什么使用枚举时的#define也同样有效? [英] Why use enum when #define is just as efficient?

查看:228
本文介绍了为什么使用枚举时的#define也同样有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,一个枚举是这样的:

So an enum works like this:

enum {
  false,
  true
}

这相当于

int false = 0
int true = 1

我为什么不代替枚举的#define

#define FALSE 0
#define TRUE 1

对我来说,好像他们是可以互换的。我知道,的#define 能够处理参数,因此比枚举完全不同的方式运作。究竟是什么枚举的主要用途时,我们有的#define 在这种情况下的?

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?

如果我是猜,因为的#define 是preprocessor功能,枚举将有一些运行时的优势。如何遥远的我是谁?

If I were to guess, as the #define is a preprocessor feature, enum would have some runtime advantages. How far off am I?

先谢谢了。

推荐答案

枚举的优势显示出来,当你有你想要映射到数字的东西很长的列表,并且希望能够在中间插入一些那名单。例如,您可以:

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 #defines, 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也同样有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆