在C中使用枚举代替

在C中使用枚举代替

本文介绍了在C中使用枚举代替#define编译时常量是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中工作一段时间后回到了一些C开发中。我已经把它放在我的头脑中,宏不应该在没有必要的时候使编译器在编译时为你做更多的工作。所以,对于常量值,在C ++中,我将使用静态const变量,或者使用C ++ 11枚举类来实现良好的范围。在C中,静态常量并不是真正的编译时常量,枚举可能(?或可能不会)的行为略有不同。

I'm coming back to some C development after working in C++ for a while. I've gotten it into my head that macros should be avoided when not necessary in favor of making the compiler do more work for you at compile-time. So, for constant values, in C++ I would use static const variables, or C++11 enum classes for the nice scoping. In C, static constants are not really compile-time constants, and enums may (? or may not?) behave slightly differently.

所以,常量的枚举而不是#define?

So, is it reasonable to prefer using enums for constants rather than #defines?

为了参考,这里是一个。

For reference, here's an excellent list of pros and cons of enums, #defines and static consts in C++.

推荐答案

我会坚持使用功能为目的。

I would stick to using the features for their purpose.

一个符号参数,在一组替代方案中取离散值,应表示为枚举成员。

A symbolic parameter, taking a discrete value among a set of alternatives, should be represented as an enum member.

数组参数,如数组大小或数值容差,应该被表示为一个常量变量。不幸的是,C没有正确的构造声明一个编译时常数(如Pascal已经),我会倾向于说一个定义的符号是同样可以接受的。我现在甚至非正统地选择使用与其他标识符相同的外壳方案的定义符号。

A numerical parameter, such as array size or numerical tolerance, should be represented as a const variable. Unfortunately, C has no proper construct to declare a compile-time constant (like Pascal had), and I would tend to say that a defined symbol is equally acceptable. I now even unorthodoxically opt for defined symbols using the same casing scheme as other identifiers.

具有显式分配值的枚举,如二进制掩码,更为有趣。有看起来挑剔的风险,我会考虑使用声明的常量,如

The enumerations with explicitly assigned values, such as binary masks, are even more interesting. At the risk of looking picky, I would consider to use declared constants, like

#define IdleMask 1
#define WaitingMask 2
#define BusyMask (IdleMask | WaitingMask)
enum Modes { Idle= IdleMask, Waiting= WaitingMask, Busy= BusyMask };

这表示,当看到编译器的任务很简单时,我不太在乎缓解编译器的任务处理他们每天收到的奇怪的代码片段。

This said, I wouldn't care so much about easing the compiler's task when you see how easily they handle the monstrous pieces of code that they receive daily.

这篇关于在C中使用枚举代替#define编译时常量是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:40