是否合理使用枚举代替#定义为编译时常使用C? [英] Is it reasonable to use enums instead of #defines for compile-time constants in C?

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

问题描述

我在C ++中工作了一段时间后回来一些C的发展。我已经得到它变成我的头,当没有必要主张使编译器在编译时为你做更多的工作,宏应避免使用。因此,对于常量值,在C ++中,我会用静态常量,或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语句合理的preFER?

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

有关参考,这里是一个在C ++枚举,#define和静态consts的利弊出色的列表。

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.

有一个象征性的参数,采取了一套备选方案之间的离散值,应重新presented作为一个枚举成员。

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

一个数值参数,如psented作为一个const变量数组的大小或数字公差,应重新$ P $。不幸的是,C有没有适当的结构来声明一个编译时间常数(例如Pascal过),我往往会说,一个定义的符号同样是可以接受的。我现在连unorthodoxically选择使用相同的外壳方案的其他标识符定义的符号。

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 };

这说,我就不会那么在乎缓解了编译器的任务,当你看到他们是如何轻松应对code的滔天件,他们每天收到。

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

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