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

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

问题描述

请考虑以下设置:

a.h

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

交流

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

int main()
{
    printf("%d\n", 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

如果用例仅涉及整数,则有更多选择.例如,您可以声明Bstatic const intenum(取决于语言),而不是宏,这显然会使用宏的当前值.如果您真的想要宏,则Boost预处理库具有 的上述#if费力的序列的实现(巧妙地减少了log(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天全站免登陆