使用宏3個值我試圖用我發現這裏的SO宏觀,但是,這個代碼給出了一些錯誤:排序用C
#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;
}
然而,當我從SWAP宏刪除do while
,它的工作原理,但給人的2,5,4
代替2,4,5
隨着SWAP宏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;
}
很容易看出,無論如何你只能執行一次交換。用一個交換對三個值(升序)進行排序是不可能的。試試吧:(2,3,1) – Ctx
你可以這個技巧來交換'a^= b; b^= a; a^= b;' – razzak
你爲什麼不能用函數而不是宏來做這個任何理由? – Lundin