C 预处理器:及早评估宏 [英] C Preprocessor: Evaluate macro early

查看:31
本文介绍了C 预处理器:及早评估宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下设置:

啊.h

#define A 5
#define B A
#undef A
#define A 3

交流

#include "a.h"
#include <stdio.h>

int main()
{
    printf("%d
", B);
    return 0;
}

虽然这非常合理地打印 3,但有没有办法让它打印 5,即在 a.h 的第二行用 5 替换 A?

While this very reasonably prints 3, is there a way to make it print 5, i.e. do the substitution of 5 for A already at line two of a.h?

推荐答案

不,没有办法做到这一点.除非你知道 A 的所有可能值,而且它们总是整数,在这种情况下你可以费力地依次测试每一个:

No, there's no way to do that. Unless you know all the possible values of A, and they are always integers, in which case you can laboriously test each one in turn:

#if A == 0
# define B 0
#elif A == 1
# define B 1
#elif A == 2
# define B 2
/*  ... and a very long etc. */
#endif

如果您的用例仅涉及整数,则您有更多选择.例如,您可以将 B 声明为 static const intenum (取决于语言)而不是宏,这显然会使用宏的当前值.如果你真的想要宏,Boost 预处理库有一个 上述#if的繁琐序列的实现(巧妙地减少了记录(N)而不是N所需的预处理器语句的数量).

If your use case only involves integers, you have more options. You could, for example, declare Bto be static const int or enum (depending on language) instead of a macro, which would obviously use the current value of the macro. If you really really want macros, the Boost preprocessing library has an implementation of the laborious sequence of #ifs above (with some cleverness to reduce the number of preprocessor statements needed to log(N) instead of N).

#define 预处理指令中没有宏替换;§6.10 段涵盖了这一事实.C 标准的第 7 条(C++ 标准的§16 第 6 段,措辞相同):

There is no macro substitution in the #define preprocessor directive; this fact is covered by §6.10 para. 7 of the C standard (§16 para. 6 of the C++ standard, with identical wording):

除非另有说明,否则预处理指令中的预处理标记不受宏扩展的影响.

The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.

#if#include 指令的描述中,标准规定确实会发生宏替换,这就是 #if 上述解决方案有效(以及 Boost 实现,它也使用计算的 #include).

In the description of the #if and #include directives, the standard specifies that macro replacement does occur, which is why the #if solution above works (and the Boost implementation, which also uses a computed #include).

这篇关于C 预处理器:及早评估宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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