C语言 - 宏 | 条件编译

■ 宏

主要功能是做替换。它的使用能让程序更加易于修改。宏不是变量,只是做标记,它不做运算优先级的检查

 1 #include <stdio.h>
 2 #define SUMVALUE(x,y)   x+y
 3 #define SUMNUM(a,b)     (a+b)
 4 
 5 int main(int argc, const char * argv[]) {
 6 
 7     // 原始语句:int a = SUMVALUE(20, 10) * SUMVALUE(10, 30);
 8     // 预处理展开后:int a = 20 + 10 * 10 + 30;
 9     int a =  SUMVALUE(20, 10)*SUMVALUE(10, 30);
10     printf("%d\n",a); // 输出结果: 150
11 
12     // 原始语句:int b = SUMNUM(20, 10) * SUMNUM(10, 30);
13     // 预处理展开后:int b = (20+10) * (10+30);
14     int b =  SUMNUM(20, 10)*SUMNUM(10, 30);
15     printf("%d\n",b); // 输出结果: 1200
16 
17     return 0;
18 }

命名规则:纯大写或者驼峰命名法

 1 #include <stdio.h>
 2 #define kCount 10 // 末尾不要加分号
 3 #define kSumValue(x,y) x+y // 有参宏
 4 #define kMaxValue(x,y) x>y ? x : y
 5 
 6 int main(int argc, const char * argv[]) {
 7     
 8     // 冒泡排序
 9     int array [kCount]={7,8,9,23};
10     for (int i=0; i<kCount-1; i++) {
11         for (int j=0; j<kCount-1-i; j++) {
12             if (array[j]>array[j+1]) {
13                 int temp = array[j];
14                 array[j]=array[j+1];
15                 array[j+1]=temp;
16             }
17         }
18     }
19     
20     for (int i=0; i<kCount; i++) {
21         printf("%d ",array[i]);
22     }
23     
24     // 
25     int sum = kSumValue(3,5);
26     printf("\n%d ",sum);
27     
28     // 比较
29     int max =kMaxValue(4,5);
30     printf("\n%d\n",max);
31     
32     return 0;
33 }

■ 条件编译

条件编译和 if 语句不同,前者是编译期执行,后者是在运行期执行

 1 #include <stdio.h>
 2 #define FUCK 0
 3 
 4 int main(int argc, const char * argv[]) {
 5 
 6 // 方式一:ifdef(如果已定义)
 7 // 只要定义了该宏(无论值是 0 还是 1),#ifdef FUCK 都会判定为 真
 8 #ifdef FUCK
 9     printf("FUCK_A\n");  // 执行此行
10 #else
11     printf("SHIT_A\n");
12 #endif
13 
14 
15 // 方式二:ifndef(如果未定义)
16 #ifndef FUCK
17     printf("FUCK_B\n");
18 #else
19     printf("SHIT_B\n");  // 执行此行
20 #endif
21 
22 
23 // 方式三:后跟常量,非 0 即真
24 #if FUCK
25     printf("FUCK 10 \n");
26 #else
27     printf("No \n");
28 #endif
29 
30 #if 5
31     printf("5\n");// 执行此行
32 #else
33     printf("10\n");
34 #endif
35 
36     return 0;
37 }

 

posted on 2017-08-02 14:51  低头捡石頭  阅读(52)  评论(0)    收藏  举报

导航