您的位置:首页 > 其它

typedef #define用法与区别

2016-04-15 13:17 465 查看
typedef定义了一种类型的别名 实际并不分配内存空间 它编译过程中的一部分

1.变量

typedef int INT;
INT a;              //a类型为int


2.指针

typedef char* PCHAR;
PCHAR a,b;     //a,b为指向字符型的指针


3.数组

Typedef char CH[8];
CH a;           //a为拥有8个元素字符型数组,a这里的大小类型都是由上面固定的


4.结构体

C语言:

typedef struct Student
{
Int a;
}Stu;
Stu b;


如果没有Student,就不能用struct去声明变量。如果没有typedef,Stu只是一个变量,它声明变量为
struct Student a
;

c++中

struct Student
{
Int a;
}Stu;       //Stu是一个变量
Stu.a;      //访问时可以直接访问


typedef struct Student
{
Int a;
}Stu;       //Stu是一个结构体类型
Stu b;
B.a;


5.函数

typedef int (*P)();     //P为指向函数的指针类型,函数返回值为int,无参数
P a,b;              //a,b为P类型的指针变量


6.为复杂变量重命名

①int *(*a[5])(int, char*);

typedef int *(*P)(int, char*);
P a[5];

②void (*b[10])(void (*)());

typedef void(*P)();
typedef void(*F)(P);
F b[10];

③double(*(*pa)[9])();

typedef double (*P)();
typedef P (*F)[9];
F pa;


7.用typedef来定义与平台无关的类型

比如定义一个叫 REAL 的浮点类型,在目标平台一上,让它表示最高精度的类型为:

typedef long double REAL
;

在不支持 long double 的平台二上,改为:

typedef double REAL
;

在连 double 都不支持的平台三上,改为:

typedef float REAL
;

注意一:

typedef和存储类关键字不能连用,比如auto,external,static,register,如
typedef static int INT
;

注意二:

typedef char* P;                //应改为typedef const char* p;
int mystrcmp(const P, const P); //这里等价于char* const p
char *string=”hello”;
const char *a=string;
const P b=string;
P const c=string;
a++;                        //√
b++;                        //×
c++;                        //× b和c一样,都是限定数据类   型为char*的变量为只读


#define是宏替换 它是预处理过程中的一部分,在自己的作用域中给一个已经存在的类型一个别名

#define P int*;                        //把出现的P,替换为int*
typedef int* F;                     //是语句
int *x和P x等价
long P x;                           //√
long F x;                           //×
P a,b;                          //a,b都为int*指针
F a,b;                          //a为int*,b为int
const P a;                          //a可更改,预处理为const int* a;
const F b;                          //b不可改,int* const b;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: