[英]Sort 3 numbers using macros [C]
Lets say we have defined macro SWAP: 可以说我们定义了宏SWAP:
#define SWAP(a,b) {\
int tmp = a; \
a = b; \
b = tmp;}\
and using SWAP we need to sort 3 numbers (just write another macro which uses macro called SWAP): 使用SWAP,我们需要对3个数字进行排序(只需编写另一个使用SWAP宏的宏):
#define SORT(a,b,c) \
(a > b) ? SWAP(a,b) : ((a > c) ? SWAP(a,c) : ((b>c) : SWAP(b,c)))
I wrote it like this but my code shows only some errors: 我是这样写的,但是我的代码只显示了一些错误:
#include <stdio.h>
#define SWAP(a,b) {\
int tmp = a; \
a = b; \
b = tmp;}\
#define SORT(a,b,c) \
(a > b) ? SWAP(a,b) : ((a > c) ? SWAP(a,c) : ((b>c) : SWAP(b,c)))
int main()
{
int a = 1024, b = 7, c = 11;
printf("a = %d b = %d\n", a, b);
SWAP(a,b)
printf("a = %d b = %d\n", a, b);
printf("a = %d b = %d c = %d\n", a, b);
SORT(a,b,c)
printf("a = %d b = %d c = %d\n", a, b);
return 0;
}
errors I get: 我得到的错误:
error: expected expression before ‘{’ token|
Let's expand your SORT(a,b,c) macro: 让我们扩展您的SORT(a,b,c)宏:
(a > b) ? SWAP(a,b) : ((a > c) ? SWAP(a,c) : ((b>c) : SWAP(b,c)))
Expanding each SWAP(a,b): 展开每个SWAP(a,b):
(a > b) ? {
int tmp = a;
a = b;
b = tmp;
} : ((a > c) ? {
int tmp = a;
a = c;
c = tmp;
} : ((b>c) : {
int tmp = b;
b = c;
c = tmp;
}))
This is not valid C code. 这不是有效的C代码。 That's why it fails to compile. 这就是为什么它无法编译。
Define it like this: 像这样定义它:
#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) }
BTW, it's a good practice, to define multiline macros using dummy do-while loops (see: C multi-line macro: do/while(0) vs scope block ): 顺便说一句,使用虚拟的do-while循环定义多行宏是一个好习惯(请参阅: C多行宏:do / while(0)vs作用域块 ):
#define SWAP(a,b) do {\
int tmp = a; \
a = b; \
b = tmp;} while(0)\
This way, you can write it like a regular function call: 这样,您可以像常规函数调用一样编写它:
SWAP(a,b);
On compiling with gcc -E the SORT macro was expanded like this 在使用gcc -E进行编译时,SORT宏就是这样扩展的
(a > b) ? {int tmp = a; a = b; b = tmp;} : ((a > c) ? {int tmp = a; a = c; c = tmp;} : ((b>c) : {int tmp = b; b = c; c = tmp;}))
The problem here are the braces and the semi colon in the SWAP function. 这里的问题是SWAP功能中的花括号和半冒号。
@Tamas Zahola you need to modify @Tamas Zahola,您需要修改
#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) }
this will not work if value of b will be greater then c in whole program. 如果b的值在整个程序中大于c,则此方法将无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.