小程序求助~
#include <stdio.h>#define PR(format,value) printf("value=%format\t",value)
void main()
{
int x=5;
PR(d,x);
}
为什么编译可以,但是运行后却报错,哪里错了呢? 鱼油你好,代码的问题在于宏定义中的格式字符串没有正确展开。
#include <stdio.h>
// 原宏定义:这里%format会被当作普通字符串,而不是格式说明符
// 展开后变成:printf("value=%format\t",x);%format不是有效格式符
// 正确写法:使用#将参数字符串化,再拼接成完整格式字符串
#define PR(format, value) printf("value=%" #format "\t", (value))
int main()// main函数应返回int类型
{
int x = 5;
PR(d, x);// 展开为:printf("value=%d\t", (5));
return 0;
}
主要问题:
1. 在字符串中的 %format 不会被替换,预处理器不会在字符串内替换宏参数
2. void main() 不符合C标准,应使用 int main()
修改后程序会正确输出:value=5(后面有制表符)
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 第3行改为这样:
#define PR(format, value) printf("value=%" #format "\t", (value))
页:
[1]