码迷,mamicode.com
首页 > 编程语言 > 详细

[C语言 - 5] 预处理

时间:2015-05-13 18:55:24      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

编译之前的处理指令

A.宏定义
a.
1 //Like static constant
2 #define NUM 6
3 
4 //The truth of macro define is replacing the constant
5 //Replace "sum(a, b)" with "a+b"
6 #define sum(a, b) a+b
实质是字符替换
 
b.带参数的宏定义
#define sum(v1,v2) v1+v2
 
但是这种“函数”有缺点
    printf("sum = %d\n", sum(1, 2) * sum(3, 4));
out:
sum = 11
因为宏定义的实质是文本替换,不会进行计算,实际计算是 1 + 2 * 3 + 4
解决:给每个变量、算式加上括号
#define sqr(a) ((a)*(a))
    printf("sqr = %d\n", sqr(5+5));
 
 
B.条件编译
条件成立的时候才进行编译
技术分享
 1 #define NUM 1
 2 
 3 int main(int argc, const char * argv[]) {
 4 
 5 #if NUM == 0
 6     printf("0");
 7 #elif NUM > 0
 8     printf(">0");
 9 #elif NUM < 0
10     printf("<0");
11 #endif
12    
13     printf("\n");
14     return 0;
15 }
技术分享
 
C.文件包含
系统自带使用<> #include <stdio.h>
自定义”” #include “mylib.h”
 
使用<>直接到系统目录中寻找资源
使用””先在源程序目录寻找,若找不到再前往系统目录
 
防止多次定义,多次引入:
#ifndef NUM
#define NUM 3
#endif
 
不能循环包含!!
 

[C语言 - 5] 预处理

标签:

原文地址:http://www.cnblogs.com/wvqusrtg/p/4500755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!