C语言 #define 还是枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3134757/
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-09-02 05:45:20  来源:igfitidea点击:

#define or enum?

c

提问by SSS

Possible Duplicate:
Why use enum when #define is just as efficient?

可能的重复:
为什么在#define 同样有效时使用枚举?

When programming in C, is it better practice to use #define statements or enums for states in a state machine?

在 C 中编程时,在状态机中使用 #define 语句或枚举来表示状态是更好的做法吗?

采纳答案by Daniel B?lu??

Since the states are related elements I think is better to have an enum defining them.

由于状态是相关元素,我认为最好有一个定义它们的枚举。

回答by Mecki

Technically it doesn't matter. The compiler will most likely even create identical machine code for either case, but an enumeration has three advantages:

从技术上讲,这无关紧要。编译器很可能甚至会为这两种情况创建相同的机器代码,但枚举具有三个优点:

  1. Using the right compiler+debugger combination, the debugger will print enumeration variables by their enumeration name and not by their number. So "StateBlahBlup" reads much nicer than "41", doesn't it?

  2. You don't have explicitly give every state a number, the compiler does the numbering for you if you let it. Let's assume you have already 20 states and you want to add a new state in the middle, in case of defines, you have to do all renumbering on your own. In case of enumeration, you can just add the state and the compiler will renumber all states below this new state for you.

  3. You can tell the compiler to warn you if a switch statement does not handle all the possible enum values, e.g. because you forgot to handle some values or because the enum was extended but you forgot to also update the switch statements handling enum values (it will not warn if there's a defaultcase though, as all values not handled explicitly end up in the default case).

  1. 使用正确的编译器+调试器组合,调试器将按枚举名称而不是编号打印枚举变量。所以“StateBlahBlup”读起来比“41”好很多,不是吗?

  2. 你没有明确地给每个州一个数字,如果你允许的话,编译器会为你编号。假设您已经有 20 个状态,并且您想在中间添加一个新状态,在定义的情况下,您必须自己重新编号。在枚举的情况下,您只需添加状态,编译器将为您重新编号此新状态下的所有状态。

  3. 如果 switch 语句没有处理所有可能的枚举值,你可以告诉编译器警告你,例如因为你忘记处理某些值或者因为枚举被扩展但你忘记更新处理枚举值的 switch 语句(它会default但是,如果有案例,则不会发出警告,因为所有未明确处理的值都以默认案例结束)。

回答by AnT

There's no definitive answer. enumoffers you scoping and automatic value assignment, but does not give any control over the constant type (always signed int). #defineignores scoping, but allows you to use better typing facilities: lets you choose the constant type (either by using suffixes or by including an explicit cast into the definition).

没有确定的答案。enum为您提供范围和自动值分配,但不提供对常量类型的任何控制(总是signed int)。#define忽略范围,但允许您使用更好的类型工具:让您选择常量类型(通过使用后缀或通过在定义中包含显式强制转换)。

So, choose for yourself what is more important to you. For a state machine, enummight be a better choice, unless you have a good reason to control the type.

因此,请为自己选择对您来说更重要的东西。对于状态机,enum可能是更好的选择,除非您有充分的理由控制类型。

回答by Adam Shiemke

I prefer enum. They are more compact and are 'safer'. You can also imply order in an enum, which might be helpful in a state machine. #defines should be avoided if possible, since they will overwrite all occurrences in source, which can lead to some unintended actions which are difficult to debug.

我更喜欢枚举。它们更紧凑,更“安全”。您还可以在枚举中暗示 order,这可能对状态机有所帮助。#defines 应该尽可能避免,因为它们会覆盖源中的所有出现,这可能导致一些难以调试的意外操作。

回答by MikeD

#definedirectives can have lots of unintended consequences and don't follow common scoping rules. Use enums when you have related data.

#define指令可能会产生许多意想不到的后果,并且不遵循通用的范围规则。当您有相关数据时使用枚举。

More information: http://www.embedded.com/columns/programmingpointers/9900402?_requestid=341945[C++ material, but still marginally relevant]

更多信息:http: //www.embedded.com/columns/programmingpointers/9900402?_requestid=341945[C++ 材料,但仍然勉强相关]

回答by Craig Trader

If enumis supported by your compiler, then that would be preferred. Failing that, by all means, use #define. All C++ compilers and modern C compilers should support enum, but older compilers (particularly ones targeting embedded platforms) may not support enum.

如果enum您的编译器支持,那将是首选。无论如何,如果失败,请使用#define. 所有 C++ 编译器和现代 C 编译器都应该enum支持enum.

If you must use #definemake sure to define your constants with parentheses, to avoid preprocessor errors:

如果必须使用,请#define确保使用括号定义常量,以避免预处理器错误:

#define RED_STATE    (1)
#define YELLOW_STATE (2)
#define GREEN_STATE  (3)

回答by Eonil

You can do this trick to make compiler check the type of #definevalue.

你可以用这个技巧让编译器检查#define值的类型。

#define VALUE_NAME ((TYPE_NAME) 12)

However the real problem of #defineis it can be redefined in application code. (Of course compiler will warn you about it.)

然而真正的问题#define是它可以在应用程序代码中重新定义。(当然编译器会警告你。)

回答by che

enumis great when you have exclusive options, but you can't use them to define bitfield flags, like this:

enum当您有独占选项时很棒,但您不能使用它们来定义位域标志,如下所示:

#define SQ_DEFAULT 0x0
#define SQ_WITH_RED 0x1
#define SQ_WITH_BLUE 0x2

void paint_square(int flags);

Then you can paint red-blue square with:

然后你可以用以下方法绘制红蓝方块:

paint_square(SQ_WITH_RED | SQ_WITH_BLUE);

...which you can't with enum.

...你不能用enum.

回答by Kumar Alok

You can use whatever you want and like.

你可以使用任何你想要和喜欢的东西。

Still as everyone is saying I would also like add up me as voting for Enums.

就像每个人都说的那样,我也想把我加起来为 Enums 投票。

Enums should always be preferred if you are using related data as in case of a State Machine, you can define order in enums also that will help in implementing the State Machine.

如果您在状态机的情况下使用相关数据,则应始终首选枚举,您也可以在枚举中定义顺序,这将有助于实现状态机。

Further enums will keep your program safe as all enums will be of its type only so they will avoid any possible confusions too.

进一步的枚举将确保您的程序安全,因为所有枚举都将仅属于其类型,因此它们也将避免任何可能的混淆。

#define should not be used in case of a state machine or related data. Anyway thats my suggestion, but there is no hard and fast rule.

#define 不应用于状态机或相关数据。无论如何,这是我的建议,但没有硬性规定。

Also I would like to add up one more point that enums will add more readability and understandability to your code if used in future or or if read by someone else. It is an important point when you are having a very large program and there are a lot of #defines in the program other than you are using for your State Machine.

另外我想再补充一点,如果将来使用或被其他人阅读,枚举将为您的代码增加更多的可读性和可理解性。当您有一个非常大的程序并且程序中有很多#defines 而不是您用于状态机的#defines 时,这一点很重要。