## 类型别名 typedef
格式: typedef 原类型名 新类型名;
- 其中原类型名中含有定义部分,新类型名一般用大写表示,以便于区别。
- 有时也可用宏定义来代替typedef的功能,但是宏定义是由预处理完成的,而typedef则是在编译 时完成的,后者更为灵活方便。
//基本数据类型
typedef int INTEGER
INTEGER a; // 等价于 int a;//也可以在别名的基础上再起一个别名
typedef int Integer;
typedef Integer MyInteger;
用typedef定义数组、指针、结构等类型将带来很大的方便,不仅使程序书写简单而且使意义更为 明确,因而增强了可读性。
//数组类型
typedef char NAME[20]; // 表示NAME是字符数组类型,数组长度为20。然后可用NAME 说明变量,
NAME a; // 等价于 char a[20];//结构体类型struct Person{int age;char *name;
};
typedef struct Person PersonType;或:
typedef struct Person{int age;char *name;
} PersonType;或:
typedef struct {int age;char *name;
} PersonType;//指针类型,typedef与指向结构体的指针//定义一个结构体并起别名typedef struct {float x;float y;} Point;// 起别名typedef Point *PP;//枚举类型
enum Sex{SexMan,SexWoman,SexOther
};
typedef enum Sex SexType;或:
typedef enum Sex{SexMan,SexWoman,SexOther
} SexType;或:
typedef enum{SexMan,SexWoman,SexOther
} SexType;
宏定义#define与函数以及typedef区别
与函数的区别
从整个使用过程可以发现,带参数的宏定义,在源程序中出现的形式与函数很像。但是两者是有本质区别的:
- 宏定义不涉及存储空间的分配、参数类型匹配、参数传递、返回值问题
- 函数调用在程序运行时执行,而宏替换只在编译预处理阶段进行。所以带参数的宏比函数具有更高的执行效率
typedef和#define的区别
- 用宏定义表示数据类型和用typedef定义数据说明符的区别。
- 宏定义只是简单的字符串替换,是在预处理完成的
- typedef是在编译时处理的,它不是作简单的代换,而是对类型说明符?重新命名。被命名的标识符具有类型定义说明的功能
typedef char *String1; // 给char *起了个别名String1
#define String2 char * // 定义了宏String2
int main(int argc, const char * argv[]) {/*只有str1、str2、str3才是指向char类型的指针变量由于String1就是char *,所以上面的两行代码等于:char *str1;char *str2;*/String1 str1, str2;/*宏定义只是简单替换, 所以相当于char *str3, str4;*号只对最近的一个有效, 所以相当于char *str3;char str4;*/String2 str3, str4;return 0;
}