使用 #define 重新定义 enum 枚举器

发布于 2024-11-26 09:57:44 字数 316 浏览 1 评论 0原文

我在 C 头文件中发现了一些我不知道其用途的东西。例如,在文件 bits/socket.h 中,有一个枚举类型 enum __socket_type,但在每个枚举器后面都有一个定义相同的宏。示例:

enum __socket_type
{
   SOCK_STREAM = 1,
   #define SOCK_STREAM SOCK_STREAM 
   ...
};

我一直无法找出它的用途。请赐教。我什至不知道如何形成正确的问题来查询谷歌或该网站的搜索框。

I have spotted something in C header files what I can't figure out what is for. For example in file bits/socket.h there is an enumeration type enum __socket_type, but after every enumerator there is a define macro which defines the same. Example:

enum __socket_type
{
   SOCK_STREAM = 1,
   #define SOCK_STREAM SOCK_STREAM 
   ...
};

I have been unable to find out what this is for. Please enlighten me. I don't even know how to form right question for querying google nor this site search box.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦毁影碎の 2024-12-03 09:57:44

预处理器宏永远不会递归扩展,因此这样的#define 所做的就是将名称保留在使用的地方。当您想要进行预处理器功能测试时,这些东西非常有用。

#ifdef SOCK_STREAM
..
#endif

可用于随后有条件地编译一些代码。

编辑:因此,这将更简洁的枚举方法(没有冲突和范围界定的隐式值)与预处理器测试结合起来。

A prepreprocessor macro will never expand recursively, so what such a #define does is leave the name in place whereever it is used. Such things are useful when you want to have a preprocessor feature test.

#ifdef SOCK_STREAM
..
#endif

can be used to conditionally compile some code afterwards.

Edit: So this combines the cleaner approach of enumerations (implicit values without collisions and scoping) with preprocessor tests.

等风也等你 2024-12-03 09:57:44

我唯一能想到的是,因为人们看到一个全大写的常量,比如 NUM_FILES,他们会认为这是一个宏,并试图这样写:

#ifdef NUM_FILES

现在通常这会失败,但是如果你编写#define NUM_FILES NUM_FILES,它的行为就像预处理器和IDE的宏以及代码本身的枚举。

The only thing I can think of is because people see a constant in all-caps, say NUM_FILES, they'll think it's a macro and are tempted to write this:

#ifdef NUM_FILES

Now normally this would fail, but if you write #define NUM_FILES NUM_FILES it behaves as a macro for the preprocessor and IDE's and as an enum for the code itself.

冷情妓 2024-12-03 09:57:44

我怀疑 IDE 或其他工具可以理解符号是以某种方式定义的。

I would suspect it's for IDEs or other tools to understand that a symbol is defined in some way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文