# 浅谈VC中define的使用方法

１、用来定义常数

例子：

#define  MAXTIME 60
int i;
for(i =0; i < MAXTIME; i++){
//todo something
}

２、定义算式

例子：

①

#define  COUNTOF(array) (sizeof(array) / sizeof(*array) )

typedef struct{
int num;
char name[20];
float score;
}student;
student stu[] ={
{1001, "zhuque", 97.5},
{1003, "zuozhu", 83 },
{1004, "minren", 83 },
{1007, "guaili", 78 },
{1010, "xiaoli", 80 }
};

const student* FindStd(int number){
int i;
const student* std;

std = stu;
printf("sizeof(stu) = %d\n", sizeof(stu));
printf("sizeof(*stu) = %d\n", sizeof(*stu));
printf("COUNTOF(stu)=%d\n",COUNTOF(stu));
for (i = 0; i < COUNTOF(stu); i++){
printf("YES YOU CAN\n");
if (std->num == number){
printf("here\n");
return std;
}
std++;
}
if( i >= COUNTOF(stu) ){
return NULL;
}
}

３、用来定义函数

#include <stdio.h>

int MAX(unsigned long, unsigned long, unsigned long);
#define RGB88(g,b) ((g)>(b)?(g):(b))
#define RGB888(r,g,b) MAX(r,g,b)

int MAX(unsigned long r, unsigned long g, unsigned long b){
return RGB88(r,RGB88(g,b));
}

int main(){
unsigned long r = 100,
g = 200,
b = 300;
printf("THE MAX NUMBER IS [%d]\n", RGB888(r,g,b));
}


４、用于结构体封装

#define GDefClass(GClassName,GSuperClass)\
struct GClassName {\
GSuperClass gscBase;

#define GDefEnd\
};

typedef struct GObject{
char * name;
int  iId;
float score;
};

GDefClass(GBaseWindow,GObject)
short nX;
short nY;
short nWidth;
short nHeight;
GDefEnd

....

GDefEnd

struct GBaseWindow {
GObject  gscBase;
short nX;
short nY;
short nWidth;
short nHeight;
}
`

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客