宏定义一些内容
預處理指令
大多數預處理指令都屬于下面3種之一:
(1)宏定義
(2)文件包含
(3)條件編譯
其它還有一些不常用的#error #line和pragma。
宏定義
(1)簡單的宏
#define PI 3.141592654(2)帶參數的宏
#define MAX(x,y) ((x)>(y)?(x):(y)) 宏定義中的圓括號對于一個宏要在哪里加圓括號有兩條規則
(1)如果宏的替換列表中有運算符,那么始終要將替換列表放在括號中間
#define TWO_PI (2*3.141592654)否則,考慮以下情況: x=360/TWO_PI若沒有括號,則變成
x=360/2*3.141592654(2)如果宏有參數,每個參數每次在替換列表中出現時都要放在原括號中 #define SCALE(x) ((x)*10)預定義宏
__LINE__
__FILE__
__DATE__
__TIME__
__STDC__
以上為C89的預定義宏,C99還有新增的。
#include <stdio.h>int main(void){printf("This program is compile on %s at %s.\n", __DATE__, __TIME__);printf("This is the line %d in file %s\n", __LINE__, __FILE__);return 0; }輸出:
[lujinhong@lujinhong CProgrammingAModernApproach]$ gcc macro_test.c
[lujinhong@lujinhong CProgrammingAModernApproach]$ ./a.out
This program is compile on Feb ?7 2013 at 23:13:10.
This is the line 5 in file macro_test.c
總結
- 上一篇: 重要的开源资源及50个c/c++源代码网
- 下一篇: 枚举作为整数