2.宏
(C的宏相当于C++的模板功能)
宏与函数的比较
如果要追求程序的运行速度,就选择用宏来实现
如果不在乎程序的大小,而是追求完整和方便维护,请选择用函数来实现
2.1定义和取消宏
定义宏名:#define 宏名 宏表达式
代码
#define _toupper(c) ((((c)>=’a’)&&((c)<=’z’)) ? (c) - ’a’ +’A’:c)
#define SUM(x,y)((x)+(y))
#define MUL(x,y)((x)*(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define MAX(x,y)((x)>(y)?(x):(y))
取消宏名:#undef 宏名
#undef _toupper(c)
#undef SUM(x,y)
#undef MUL(x,y)
2.2判断相关符号是否被定义
代码格式
#ifndef/ifdef [符号名]
代码行...
#endif
(#ifndef是没有定义,ifdef是已经定义)
代码实例
#ifndef SUM(x,y)
#define SUM(x,y)((x)+(y))
printf("ONlY IS A TEST,SUM(3,5)=%d\n",SUM(3,5));
#endif
2.3对宏进行if-else条件处理
#ifdef symbol
//statements...
#else
//other statements...
#endif
或者
#ifndef symbol
//statements...
#else
//other statements...
#endif
代码实例1
#ifndef LIBTYPE
#include "mylib1.h"
#else
#include "mylib2.h"
#endif
代码实例1
#ifdef ADDONCE
#include "mylib1.h"
#else
#include "mylib2.h"
#endif
责任编辑:小草