C提供的预处理功能主要3种:
- 宏定义
- 文件包含
- 条件编译
- 宏定义
不带参数宏定义: #define 标识符 字符串
带参数的宏定义: #define 宏名(参数表) 字符串
- 文件包含
“文件包含”处理指一个源文件可以将另外一个源文件的全部内容包含进来,即将另外的文件包含到本文件中。
一般形式为:
#include“文件名” 或 #include<文件名>
- 条件编译
条件编译命令几种形式:
1)#ifdef 标识符 //检测标识符已定义
程序段1
#else //#else可省略
程序段2
#endif
2)#ifndef 标识符 //检测标识符未定义
程序段1
#else //#else可省略
程序段2
#endif
3)#if 表达式 //检测表达式为真(非0)
程序段1
#else //#else可省略
程序段2
#endif
宏定义的头文件:
/*format.h文件*/
#define INTEGER(d) printf("%d\n",d) //输出整数
#define FLOAT(f) printf("%8.2f\n",f) //输出实数
#define STRING(s) printf("%s\n",s) //输出字符串
文件包含源文件:
/*用format.h文件中的输出格式*/
#include<stdio.h>
#include"format.h"
void main() {
int d,num;
float f;
char s[80];
printf("choice data format: 1-integer,2-float,3-string:");
scanf_s("%d",&num);
switch(num) {
case 1: printf("input integer:");
scanf_s("%d",&d);
INTEGER(d);
break;
case 2: printf("intput float:");
scanf_s("%f",&f);
FLOAT(f);
break;
case 3: printf("input string:");
scanf_s("%s",s,80);
//数组名s代表数组起始地址,不用地址符&
//80:scanf_s(),在调用时,必须提供一个数字以表明最多读取多少(80)位字符
//此处可用scanf("%s",s),读取时不检查边界,所以可能会造成内存泄露
//不能用scanf_s("%s",s),无法读取字符
STRING(s);
break;
default: printf("input error!");
}
}