第10章 高级语言程序设计C--编译预处理.ppt

第10章 高级语言程序设计C--编译预处理

例10-4 编译指令#undef的使用 #includestdio.h #define NAME Tsinghua Uni.\n /* 定义了宏NAME */ void main(void) { #ifdef NAME printf(NAME); /* 参加编译 */ #endif #undef NAME /* 取消了宏NAME 的定义 */ #ifndef NAME /* 没有定义宏NAME */ printf(“NAME doesn\‘t mean \”Tsinghua Uni.\“\n”); /* 参加 编译 */ #endif } 10.5 #undef 程序运行情况如下: Tsinghua Uni. NAME doesnt mean Tsinghua Uni. 说明: 因为开始时已经定义了宏NAME,所以输出宏NAME所代表的串,后面取消了宏NAME的定义,所以输出NAME doesnt mean Tsinghua Uni.。 10.5 #undef 计算机科学与技术学院—— C语言程序设计 计算机科学与技术学院系——数据结构 计算机科学与技术学院系——数据结构 第十章 编译预处理 华侨大学计算机科学与技术学院 刘韶涛 副教授 第十章 编译预处理 内容提要 C预处理程序 #define #include 条件编译指令 #undef 10.1 C预处理程序 按照ANSI标准的定义,C预处理程序应处理如下指令: #if #ifdef #ifndef #else #elif #define #undef 10.1 C预处理程序 #line #error #pragma 显然,所有的预处理指令都以#开始。而且,每条预处理指令必须独占一行。例如: #includestdio.h #includestdlib.h 是错误的。 本章我们只介绍一些最常用的指令,其它指令的使用,请大家需要时参考有关书籍。 10.1 C预处理程序 第十章 编译预处理 内容提要 C预处理程序 #define #include 条件编译指令 #undef 10.2 #define #define指令定义一个标记符和一个串,在源程序中发现该标记符时,都用该串替换之。ANSI标准中称这种标记符为宏名字(macro name),称相应的替换为宏替换(macro substitution)。这种指令的一般形式为: #define 宏名 串 这种语句不用分号结尾。宏名字与串之间可以有多个空白符,但串开始后只能以新行符(newline结尾)。比如: #define TRUE 1 #define FALSE 0 printf(“%d %d %d\n”,FALSE,TRUE,TRUE+1); /* 显示0 1 2 */ 10.2 #define 说明: (1)宏定义之后,编译程序将程序中的TRUE和FALSE都替换为1和0。所以显示结果为0 1 2。 (2)定义一个宏名字之后,可以在其他宏定义中使用它。如: #define ONE 1 #define TWO ONE+1 #define THREE ONE+TWO 10.2 #define 例10-1 宏定义及其使用 #define MESSAGE “You are right!\n” #define LONG_STRING “This is a very long string\ that is used as a example\n” #define ABS(a) (a)0?-(a):(a) void main(void){ printf(MESSAGE); /* 输出:You are right! */ printf(“MESSAGE\n”); /* 输出:MESSAGE */ printf(LONG_STRING); /* 输出:This is a very long string that is used as an example */ printf(“abs of -1 and 1 : %d %d\n”,ABS(-1),ABS(1)); } 10.2 #define 程序运行情况如下: You are right! MESSAGE This is a very long string that is used as an example abs of -1 and 1 : 1 1 10.2 #define 说明: (1)遇到标识符MESSAGE时,编译程序用串” You

文档评论(0)

1亿VIP精品文档

相关文档