是否存在使用编译器指令宏的 itoa 替代方案
我想知道是否有一种方法可以使用字符串化编译器指令来字符串化整数变量。 我尝试使用:
#define stringize(a) #a
#define h(a) stringize(a)
#define g(a,b) a##b
#define f(a,b) g(a,b)
int main()
{
int num = 1024;
printf("%s=%s\n",stringize(h(f(1,2))), h(f(1,2))); //1. h(f(1,2))=12
printf("%s=%s\n",h(h(f(1,2))), h(f(1,2))); //2. "12"=12
printf("%s=%d\n", h(num),num); //num=1024
return 0;
}
因此在 stringize 宏(#1)中添加另一个级别将首先进行替换,然后将其放入代码(#2)中,以类似的方式可以在编译时用值替换变量。 我的意思是说 if var = value;那么有什么方法可以 some_macro(var) -->;可以将其字符串化为“值”吗?
I was wondering is there can be a way to stringize an integer variable using stringizing compiler directive.
I tried using:
#define stringize(a) #a
#define h(a) stringize(a)
#define g(a,b) a##b
#define f(a,b) g(a,b)
int main()
{
int num = 1024;
printf("%s=%s\n",stringize(h(f(1,2))), h(f(1,2))); //1. h(f(1,2))=12
printf("%s=%s\n",h(h(f(1,2))), h(f(1,2))); //2. "12"=12
printf("%s=%d\n", h(num),num); //num=1024
return 0;
}
so as adding another level in stringize macro(#1) will make the substitution to happen first then placing it in code(#2), in similar way can variables be replaced at compile time with the values.
I mean to say if var = value; then is there some way that
some_macro(var) --> can stringize it into "value"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法使用预处理器获取变量的值 - 预处理(顾名思义)发生在编译之前,并且变量在该阶段不存在。
There's no way of getting the value of a variable using the preprocessor - preprocessing (as its name suggests) takes place before compilation, and the variables do not exist at that stage.
不。预处理器作用于标记,它不知道变量及其值。如果从 stdin 读取该值,您希望得到什么?
No. The preprocessor is acting on tokens, it doesn't know about variables and their values. What would you want to get if the value was read from stdin?