Utility of macros for enum

房东的猫 提交于 2019-12-05 00:27:57

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.

From the POSIX standard:

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

And:

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

And finally, from an appendix:

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

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.

The purpose of these defines is that the application can do something like

#ifdef MSG_OOB
  some code here
#endif

expansion of macros is not recursive so the evaluation of macro MSG_OOB results in the enum constant MSG_OOB of the same name.

To also have the constants declared as enum helps for example when you are debugging.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!