gpt4 book ai didi

c - 无法解析 C 中的宏优先级?

转载 作者:太空狗 更新时间:2023-10-29 17:08:15 27 4
gpt4 key购买 nike

我正在尝试编写一个简单的 C 程序。这里我定义了一个宏。

#define NAME(x) #x ## _bingo

现在哪一个(###)先被解决?

我卡住了 :) 。我试图用谷歌搜索这种宏优先级。但是找不到任何相关的东西。

最佳答案

Now which one (# and ##) of them will be solved first?

标准说:

16.3.2 The # operator [cpp.stringize]

2/ [...] The order of evaluation of # and ## operators is unspecified.

但是你想在这里实现什么?似乎是:

#define NAME(x) x ## _bingo

如果您想连接 x 标记和 _bingo 就足够了。

例子:

NAME(foo)

将扩展为

foo_bingo

编辑:

如果你想用NAMEstringify生成的token,这里有一个例子说明如何做到这一点(解决宏替换问题-> < em>标准的16.3.1):

#define NAME(x)  x##_bingo

// Converts the parameter x to a string after macro replacement
// on x has been performed if needed.
#define STRINGIFY(x) DO_STRINGIFY(x)
#define DO_STRINGIFY(x) #x

int main() {
std::string n = STRINGIFY( NAME( foo ) );
std::string n2 = DO_STRINGIFY( NAME(foo) );

// Will print foo_bingo as expected
std::cout << n << std::endl;

// Will print NAME( foo ) because the macro NAME is not expanded
std::cout << n2 << std::endl;
return 0;
}

输出:

foo_bingo
NAME(foo)

关于c - 无法解析 C 中的宏优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com