C 对于带参数的宏,左值必须作为赋值的左操作数
我正在尝试使用宏作为参数多次打印字符串“x”,代码如下:-C 对于带参数的宏,左值必须作为赋值的左操作数,c,macros,lvalue,C,Macros,Lvalue,我正在尝试使用宏作为参数多次打印字符串“x”,代码如下:- 1 #include<string.h> 2 #include<stdio.h> 3 #define print(x,c) while(x>0)\ 4 {\ 5 puts(c);\ 6 printf("\n");\ 7 --x;\ 8 } 9 10 int main() 11 { 12 char c[20];
1 #include<string.h>
2 #include<stdio.h>
3 #define print(x,c) while(x>0)\
4 {\
5 puts(c);\
6 printf("\n");\
7 --x;\
8 }
9
10 int main()
11 {
12 char c[20];
13 strcpy(c,"Hallelujah");
14 print(5,c);
15 }
我无法解决这个问题,请帮忙谢谢。宏由预处理器展开,结果交给编译器 您的代码将扩展为:
int main()
{
char c[20];
strcpy(c,"Hallelujah");
while(5>0)
{
puts(c);
printf("\n");
--5;
}
}
如您所见,在每个实例中,x
被替换为实际的参数表达式。它不像常规函数中的参数变量是表达式值的本地副本那样工作
我建议您要么将宏转换为C函数,要么在调用宏之前声明一个变量来保存该值
第二个选项如下所示:
int n = 5;
print(n,c);
在marco扩展之后,此声明
print(5,c);
变成
while(5>0) { puts(c); printf("\n"); --5; };
正如您所看到的,您不能减少文本值(--5
)。您需要一个变量(可修改的左值)才能实现这一点。你的马可看起来多余。您可以简单地使用循环:
int x = 5;
while(x > 0) {
puts(c);
printf("\n");
--x;
}
如果确实要使用宏,则可以执行以下操作:
#define print(x,c) do { \
int t = x; \
while(t>0) {\
puts(c);\
printf("\n");\
--t;\
} \
} while(0)
因为你不能用c语言写
--5
!我认为你把宏和函数调用混淆了<代码>5未分配到此处的x
。
#define print(x,c) do { \
int t = x; \
while(t>0) {\
puts(c);\
printf("\n");\
--t;\
} \
} while(0)