1、宏定义开关和debug printf
#define DEBUG_PRINT 1
#ifdef DEBUG_PRINT
#define DEBUG(format, ...) printf("FILE: "__FILE__", LINE: %d: "format"\n", __LINE__, ##__VA_ARGS__)
#else
#define DEBUG(format, ...)
#endif
宏定义DEBUG(str) 只支持一个参数的替换
自C99规范以后,编译器就开始支持不定参数的宏定义
#define DEBUG(format, ...) printf("FILE: "__FILE__", LINE: %d: "format"\n", __LINE__, ##__VA_ARGS__)
注释1:##代表 如果可变参数被忽略或为空,将使得预处理器(perprocessor)会去掉它前面的那个逗号
注释2:ANSI C标准中有几个标准预定义宏,__FILE__ 文件名,__LINE___ 行号
2、宏定义使用异或交换两数
#define swap(a, b) do{ \
(a) = (a) ^ (b); \
(b) = (b) ^ (a); \
(a) = (a) ^ (b); \
}while(0);
注释1:异或,相同为0,不同为1;与0异或不变,与1异或相反;异或满足交换律
1 #include <stdio.h>
2
3 #define DEBUG_PRINT 1
4
5 #ifdef DEBUG_PRINT
6 // 可变参数的宏定义替换
7 // ##代表 如果可变参数为空,预处理器将去掉前面的逗号
8 // 标准预定义宏 __FILE__文件名,__LINE__行号
9 #define DEBUG(format, ...) printf("FILE: "__FILE__", LINE: %d: "format"\n", __LINE__, ##__VA_ARGS__)
10 #else
11 #define DEBUG(format, ...)
12 #endif
13
14 #define swap(a, b) do{ \
15 (a) = (a) ^ (b); \
16 (b) = (b) ^ (a); \
17 (a) = (a) ^ (b); \
18 }while(0);
19
20 void bubble_sort_min(int *a, int len);
21
22 int main(int argc, char *argv[])
23 {
24 int array[] = {3,4,5,6,2,7,0};
25 int len = sizeof(array) / sizeof(int);
26 int i;
27 DEBUG("before sort: ");
28 for(i=0; i<len; i++)
29 DEBUG("%d ", array[i]);
30 DEBUG("\n");
31
32 bubble_sort_min(array, len);
33
34 DEBUG("after sort: ");
35 for(i=0; i<len; i++)
36 printf("%d ", array[i]);
37 printf("\n");
38 return 0;
39 }
40
41 void select_sort_min(int *a, int len)
42 {
43 int i, j;
44
45 for(i=0; i<len-1; i++)
46 for(j=i+1; j<len; j++)
47 {
48 if(a[j] < a[i])
49 swap(a[j], a[i]);
50 }
51
52 }
53
54 void bubble_sort_min(int *a, int len)
55 {
56 int i, j;
57 for(i=0; i<len-1; i++)
58 for(j=0; j<len-1; j++)
59 if(a[j] > a[j+1])
60 swap(a[j], a[j+1]);
61 }