gpt4 book ai didi

c - 字符串化括号消除

转载 作者:行者123 更新时间:2023-12-02 03:22:51 25 4
gpt4 key购买 nike

在 c 中,我在现有代码库中有以下内容:

#define MYVAR (1)

正如您所看到的,通过用括号将 #define 括起来,这符合 C 中的良好实践(尽管我知道在这种情况下它没有什么区别,因为该值不是一种表达)。无论如何,我想在字符串化中使用它。当我这样做时:

#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)

const char* mystring = TO_STRING(MYVAR) ;

结果字符串是“(1)”。我想消除括号而不做简单的事情:

#define MYVAR 1

在c中的字符串化过程中是否有办法消除括号?

最佳答案

只需使用STRINGIFY x而不是STRINGIFY(x)

#include <stdio.h>

#define MYVAR 1

#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY x

int main(void)
{
const char *mystring = TO_STRING(MYVAR);

printf("%s\n", mystring);
return 0;
}
MYVAR 定义为 (1) 时,

TO_STRING(x) 扩展为 STRINGIFY (1)

如果 MYVAR 定义为不带括号的 1,则会出现编译时错误。

关于c - 字符串化括号消除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447423/

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