宏定义一些内容

预处理指令

大多数预处理指令都属于下面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


原文地址:https://www.cnblogs.com/eaglegeek/p/4558034.html