辅导:C预处理和宏
来源:优易学  2011-9-11 13:08:47   【优易学:中国教育考试门户网】   资料下载   IT书店

  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

上一页  [1] [2] [3] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训