C++ 枚举和定义语句之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/136946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:08:00  来源:igfitidea点击:

Difference between Enum and Define Statements

c++cenumsc-preprocessor

提问by Zain Rizvi

What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?

在 C/C++ 中使用 define 语句和 enum 语句有什么区别(在 C 或 C++ 中使用它们时有什么区别)?

For example, when should one use

例如,什么时候应该使用

enum {BUFFER = 1234}; 

over

超过

#define BUFFER 1234   

回答by Jason Cohen

enumdefines a syntactical element.

enum定义一个句法元素。

#defineis a pre-preprocessor directive, executed beforethe compiler sees the code, and therefore is not a language element of C itself.

#define是一个预处理器指令,编译器看到代码之前执行,因此不是 C 本身的语言元素。

Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #definemade by another. This can be hard to track down.

通常首选枚举,因为它们是类型安全的并且更容易被发现。定义更难定位并且可能具有复杂的行为,例如一段代码可以重新定义#define另一个代码。这可能很难追踪。

回答by paxdiablo

#definestatements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).

#define语句在编译器看到代码之前由预处理器处理,所以它基本上是一个文本替换(实际上,使用参数等会更智能一些)。

Enumerations are part of the C language itself and have the following advantages.

枚举是 C 语言本身的一部分,具有以下优点。

1/ They may have type and the compiler can type-check them.

1/ 它们可能有类型,编译器可以对它们进行类型检查。

2/ Since they are available to the compiler, symbol information on them can be passed through to the debugger, making debugging easier.

2/ 因为它们对编译器是可用的,所以它们的符号信息可以传递给调试器,使调试更容易。

回答by akiva

Define is a preprocessor command, it's just like doing "replace all" in your editor, it can replace a string with another and then compile the result.

定义是一个预处理器命令,它就像在编辑器中执行“全部替换”一样,它可以将一个字符串替换为另一个字符串,然后编译结果。

Enum is a special case of type, for example, if you write:

Enum 是 type 的一种特殊情况,例如,如果您编写:

enum ERROR_TYPES
{
   REGULAR_ERR =1,
   OK =0
}

there exists a new type called ERROR_TYPES. It is true that REGULAR_ERR yields to 1 but casting from this type to int should produce a casting warning (if you configure your compiler to high verbosity).

存在一种名为 ERROR_TYPES 的新类型。REGULAR_ERR 确实会产生 1,但是从这种类型转换为 int 应该会产生转换警告(如果您将编译器配置为高详细度)。

Summary: they are both alike, but when using enum you profit the type checking and by using defines you simply replace code strings.

总结:它们都是相似的,但是当使用 enum 时,您可以进行类型检查,而通过使用定义,您只需替换代码字符串。

回答by Simon Buchan

Enums are generally prefered over #define wherever it makes sense to use an enum:

在使用枚举有意义的地方,枚举通常比 #define 更受欢迎:

  • Debuggers can show you the symbolic name of an enums value ("openType: OpenExisting", rather than "openType: 2"
  • You get a bit more protection from name clashes, but this isn't as bad as it was (most compilers warn about re#defineition.
  • 调试器可以向您显示enums 值的符号名称(“ openType: OpenExisting”,而不是“ openType: 2
  • 您可以从名称冲突中获得更多保护,但这并没有以前那么糟糕(大多数编译器都警告重新#define定义。

The biggest difference is that you can use enums as types:

最大的区别是您可以使用枚举作为类型:

// Yeah, dumb example
enum OpenType {
    OpenExisting,
    OpenOrCreate,
    Truncate
};

void OpenFile(const char* filename, OpenType openType, int bufferSize);

This gives you type-checking of parameters (you can't mix up openType and bufferSize as easily), and makes it easy to find what values are valid, making your interfaces much easier to use. Some IDEs can even give you intellisensecode completion!

这使您可以对参数进行类型检查(您不能轻易混淆 openType 和 bufferSize),并且可以轻松找到哪些值是有效的,从而使您的接口更易于使用。一些 IDE 甚至可以为您提供智能感知代码完成!

回答by unwind

It's always better to use an enum if possible. Using an enum gives the compiler more information about your source code, a preprocessor define is never seen by the compiler and thus carries less information.

如果可能,最好使用枚举。使用枚举为编译器提供了有关源代码的更多信息,编译器永远不会看到预处理器定义,因此携带的信息更少。

For implementing e.g. a bunch of modes, using an enum makes it possible for the compiler to catch missing case-statements in a switch, for instance.

例如,为了实现一堆模式,使用枚举可以让编译器case在 switch 中捕获丢失的-statements。

回答by Andy

enum can group multiple elements in one category:

枚举可以将多个元素归为一类:

enum fruits{ apple=1234, orange=12345};

while #define can only create unrelated constants:

而#define 只能创建不相关的常量:

#define apple 1234
#define orange 12345

回答by kriss

#define is a preprocessor command, enum is in the C or C++ language.

#define 是预处理器命令,enum 是 C 或 C++ 语言。

It is always better to use enums over #define for this kind of cases. One thing is type safety. Another one is that when you have a sequence of values you only have to give the beginning of the sequence in the enum, the other values get consecutive values.

对于这种情况,最好在 #define 上使用枚举。一件事是类型安全。另一个是当你有一个值序列时,你只需要在枚举中给出序列的开头,其他值就会得到连续的值。

enum {
  ONE = 1,
  TWO,
  THREE,
  FOUR
};

instead of

代替

#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4

As a side-note, there is still some cases where you may have to use #define (typically for some kind of macros, if you need to be able to construct an identifier that contains the constant), but that's kind of macro black magic, and very very rare to be the way to go. If you go to these extremities you probably should use a C++ template (but if you're stuck with C...).

作为旁注,在某些情况下,您可能必须使用 #define(通常用于某种宏,如果您需要能够构造一个包含常量的标识符),但那是一种宏黑魔法,而且非常非常罕见。如果你走到这些极端,你可能应该使用 C++ 模板(但如果你坚持使用 C...)。

回答by ShinTakezou

Besides all the thing already written, one said but not shown and is instead interesting. E.g.

除了已经写的所有东西,还有一个说但没有显示,而是有趣的。例如

enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };
//...
void do_action( enum action anAction, info_t x );

Considering action as a type makes thing clearer. Using define, you would have written

将动作视为一种类型会使事情更清楚。使用定义,你会写

void do_action(int anAction, info_t x);

回答by Michael Burr

For integral constant values I've come to prefer enumover #define. There seem to be no disadvantages to using enum(discounting the miniscule disadvantage of a bit more typing), but you have the advantage that enumcan be scoped, while #defineidentifiers have global scope that tromps everything.

对于整型常量的值我是来更喜欢enum#define。使用似乎没有任何缺点enum(忽略更多输入的微小缺点),但是您具有enum可以限定范围的优势,而#define标识符具有全局范围,可以超越一切。

Using #defineisn't usually a problem, but since there are no drawbacks to enum, I go with that.

使用#define通常不是问题,但由于 没有缺点enum,所以我同意。

In C++ I also generally prefer enumto const inteven though in C++ a const intcan be used in place of a literal integer value (unlike in C) because enumis portable to C (which I still work in a lot) .

在C ++中我也一般喜欢enumconst int即使在C ++中const int,可以代替文字的整数值(不像C)的使用,因为enum被移植到C(我仍然有很多工作)。

回答by Henno Brandsma

If you only want this single constant (say for buffersize) then I would not use an enum, but a define. I would use enums for stuff like return values (that mean different error conditions) and wherever we need to distinguish different "types" or "cases". In that case we can use an enum to create a new type we can use in function prototypes etc., and then the compiler can sanity check that code better.

如果你只想要这个单一的常量(比如缓冲区大小),那么我不会使用枚举,而是使用定义。我会将枚举用于返回值(这意味着不同的错误条件)以及我们需要区分不同“类型”或“案例”之类的东西。在这种情况下,我们可以使用枚举来创建可以在函数原型等中使用的新类型,然后编译器可以更好地检查该代码。