是什么让一个在C更好的常数,宏或枚举? [英] What makes a better constant in C, a macro or an enum?

查看:79
本文介绍了是什么让一个在C更好的常数,宏或枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感到困惑时使用宏或枚举。既可以作为常量,但它们之间有什么区别,什么是一方的优势在哪里?是它在某种程度上关系到编译器的水平或没有?

I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it somehow related to compiler level or not?

推荐答案

在可读性方面,枚举做出比宏更好的常量,因为相关的值组合在一起。此外,枚举定义了一个新的类型,所以你的程序的读者将有更容易的时间搞清楚什么可以传递给相应的参数。

In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, enum defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter.

比较

#define UNKNOWN  0
#define SUNDAY   1
#define MONDAY   2
#define TUESDAY  3
...
#define SATURDAY 7

typedef enum {
    UNKNOWN
,   SUNDAY
,   MONDAY
,   TUESDAY
,   ...
,   SATURDAY
} Weekday;

这是很容易阅读code这样的

It is much easier to read code like this

void calendar_set_weekday(Weekday wd);

比这个

void calendar_set_weekday(int wd);

因为你知道哪个常数是确定通过。

because you know which constants it is OK to pass.

这篇关于是什么让一个在C更好的常数,宏或枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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