关于define

来源:互联网 发布:金融很虚 知乎 编辑:程序博客网 时间:2024/06/06 05:09
#define TWO 2
#define LD "my name is ldong"
#define LZ "my name is liang\
zhen" //反斜杠可以把定义延伸到下一行但是要顶格写

另外
在#define 中使用参数(类函数宏)
用括号括起一个或多个参数 #define MEAN(X,Y) (((X)+(Y))/2)
#define square(x) x*x
在程序中可使用 z = square(2); //看上去像函数调用 
 z = square(2+3) 宏只是将参数进行字符串替换,不会考虑到运算先后的问题,

这就是为什么要把每个参数都用括号括起
z = 2+3*2+3 ; 则z = 11, 而不是25


用define创建字符串
#define PSQR(X) printf("the square of X is%d.\n",((X)*(X)))
使用 PSQR(8);
输出结果:the suqare of X is 64.
如果:#define PSQR(X) printf("the square of #X is%d.\n",((X)*(X)))
则结果是:the suqare of 8 is 64.
如果X是一个宏参量,#可以吧参数名转化为相应的字符串。

#undef 取消宏定义 使用方法:

#define LIMIT 32
#undef  LIMIT  

其他指令
#ifndef #ifdef #if #else #elif #endif
例子:
#ifdef MAVIS
    #include "horse.h" 
    #define STABLES 5
#else
    #include "cow.h"
    #define STABLES 15
#endif 

同理:
#ifndef LDONG
    #include "liang.h"
    #define LD 16
#else 
    #include "dong.h"
    #define LD 32
#endif

另外: #if #elif #else
#if MAVIS == 1
    #include "xxxxx.h"
    #define LDONG xx
#elif MAVIS == 2
    #include ""
   #define 
#else 
    #include
    #define
#endif

另外:不存在这种宏定义的方法  #define  SUM(int x, int y) x+y

非常感谢郭神的帮助,郭神千秋万载一统江湖