我试图使用我在这里找到的宏,但是,这段代码出现了一些错误:
#include <stdio.h>
#include <math.h>
#define SWAP(a,b) do {\
int tmp = a; \
a = b; \
b = tmp;} while(0)\
#define SORT(a,b,c) \
if(a > b) { SWAP(a,b) } else if(a > c) { SWAP(a,c) } else if (b>c) { SWAP(b,c) }
int main()
{
int a = 5, b = 2, c = 4;
printf("a = %d, b = %d, c = %d\n", a, b, c);
SORT(a,b,c);
printf("a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}但是,当我从交换宏中删除do while时,它可以工作,但是提供2,5,4而不是2,4,5。
在交换宏中使用do ... while循环时,我的代码会给出错误:
Untitled2.c||In function ‘main’:|
Untitled2.c|10|error: expected ‘;’ before ‘}’ token|
Untitled2.c|18|note: in expansion of macro ‘SORT’|
Untitled2.c|10|error: expected ‘}’ before ‘else’|
Untitled2.c|18|note: in expansion of macro ‘SORT’|
Untitled2.c|10|error: expected ‘;’ before ‘}’ token|
Untitled2.c|18|note: in expansion of macro ‘SORT’|
Untitled2.c|10|error: expected ‘}’ before ‘else’|
Untitled2.c|18|note: in expansion of macro ‘SORT’|
Untitled2.c|10|error: expected ‘;’ before ‘}’ token|
Untitled2.c|18|note: in expansion of macro ‘SORT’|
Untitled2.c|23|error: expected declaration or statement at end of input|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|编辑:
修改了代码,但是结果是错误的,代码给了我2,5,4而不是2,4,5
#include <stdio.h>
#include <math.h>
#define SWAP(a,b) do {\
int tmp = a; \
a = b; \
b = tmp;} while(0);
#define SORT(a,b,c) \
if(a > b) { SWAP(a,b); } else if(a > c) { SWAP(a,c); } else if (b>c) { SWAP(b,c) }
int main()
{
int a = 5, b = 2, c = 4;
printf("a = %d, b = %d, c = %d\n", a, b, c);
SORT(a,b,c);
printf("a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}发布于 2016-01-25 12:46:09
在;宏中,您在SWAP(a,c)和SWAP(b,c)之后缺少了SORT。
也在这里
#define SORT(a,b,c) \
if(a > b) { SWAP(a,b) } else if(a > c) { SWAP(a,c) } else if (b>c) { SWAP(b,c) }使用else是错误的。为了对三个值( a、b和c )进行排序,应该是
#define SORT(a,b,c) \
{ \
if((a) > (b)) { SWAP(a,b); } \
if((a) > (c)) { SWAP(a,c); } \
if((b) > (c)) { SWAP(b,c); } \
}编辑
添加了( ) for a、b和c,因为它们可能代表复杂表达式。
发布于 2016-01-25 12:45:03
您需要一个分号来终止do-while循环。
b = tmp;} while(0);
^ here您的swap逻辑也是错误的。将其定义为:
if(a > b) { SWAP(a,b) } if(b > c) { SWAP(b,c) } if (a>b) { SWAP(a,b) }但是..。
整个马可的事情都很混乱。最好直接使用if- use语句,或者使用simpl inline函数。
宏是简单的文本替换,有许多固有的问题:-它们不是类型错误。-有副作用的宏参数会导致意想不到的问题。考虑:
#define SQR(x) ((x)*(x))
SQR(x++); 通常,除非您没有任何其他选项,否则不要使用宏。
发布于 2016-01-25 12:43:09
在第一个宏的末尾有一个额外的连续字符\。在SWAP()后面需要分号,因为你有while (0)。
这样,宏的行为就像它们是函数一样。
#define SWAP(a, b) \
do { \
int d; \
d = a; \
a = b; \
b = d; \
} while (0)
#define SORT(a, b, c) \
do { \
if (a > b) \
SWAP(a, b); \
else if (a > c) \
SWAP(a, c); \
else if (b > c) \
SWAP(b, c); \
} while (0)do { ... } while (0)的目的是用分号终止多语句宏,当然,在SWAP的情况下,它还为临时变量d提供了一个作用域。但是对于这个范围,您只需要使用大括号{ ... },但是在宏调用的末尾添加一个分号将创建一个空语句,因此do { ... } while (0)是解决这个问题的一个很好的技巧。
https://stackoverflow.com/questions/34992926
复制相似问题