宏枚举的效用 [英] Utility of macros for enum

查看:139
本文介绍了宏枚举的效用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个头 socket.h中在我的Linux系统看起来像下面这样。

One header socket.h on my Linux system looks like the following.

/* Bits in the FLAGS argument to `send', `recv', et al.  */
enum
  {
    MSG_OOB             = 0x01, /* Process out-of-band data.  */
#define MSG_OOB         MSG_OOB
    MSG_PEEK            = 0x02, /* Peek at incoming messages.  */
#define MSG_PEEK        MSG_PEEK
    MSG_DONTROUTE       = 0x04, /* Don't use local routing.  */
#define MSG_DONTROUTE   MSG_DONTROUTE
...

定义一个枚举是排序的<一个href=\"http://stackoverflow.com/questions/17125505/what-makes-a-better-constant-in-c-a-macro-or-an-enum\">idiom在C创建类型安全的杂交常数的是,语言实际上把编译时的常量。

Defining an enum is sort of an idiom for creating type-safe-ish constants in C that the language actually treats as compile-time constants.

我的问题是:宏定义 MSG_OOB MSG_PEEK ,...展开什么样的目的,以自己的服务?

My question is : what purpose does the definition of macros MSG_OOB, MSG_PEEK, … that expand to themselves serve?

推荐答案

POSIX标准的任务是符号常量,如 MSG_DONTROUTE 是类似对象的宏而不是enumerants。他们定义自己允许他们在枚举的范围内使用,并与正常工作,例如, #IFDEF

The POSIX standard mandates that "symbolic constants" such as MSG_DONTROUTE be "object-like macros", rather than enumerants. Defining them to themselves allows them to be used in the context of the enumeration, as well as working properly with, e.g., #ifdef.

从POSIX标准:

头应当载明下列符号常量
  ....
  MSG_DONTROUTE

The header shall define the following symbolic constants .... MSG_DONTROUTE

符号常量...是指C preprocessor符号(也没有参数)。

symbolic constant... refers to a C preprocessor symbol (also without arguments).

最后,从附录:

如果需要恒定做个宏,但也允许是另一种类型的常量,如枚举常量,在实现其做它定义为另一种类型的恒定,宏通常定义如下:

Where a constant is required to be a macro but is also allowed to be another type of constant such as an enumeration constant, on implementations which do define it as another type of constant the macro is typically defined as follows:

的#define MACRO_NAME MACRO_NAME

这允许应用程序使用#IFDEF等来判断是否宏定义,但宏是不是在#if preprocessor指令使用,因为在preprocessor将把未展开字MACRO_NAME为具有零值。

This allows applications to use #ifdef, etc. to determine whether the macro is defined, but the macro is not usable in #if preprocessor directives because the preprocessor will treat the unexpanded word macro_name as having the value zero.

这篇关于宏枚举的效用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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