例:
typedef int INTEGER;
typedef Integer MyInteger;
typedef char NAME[20]; // 表示NAME是字符数组类型,数组长度为20。然后可用NAME 说明变量。
NAME a; // 等价于 char a[20];
typedef char * String;
String myString = "hello";
与结构体的声明定义一样,在对结构体使用typedef时,也有三种形式:
struct Person{
int age;
char *name;
};
typedef struct Person PersonType; // PersonType person; person.age = ...
/
typedef struct Person{
int age;
char *name;
} PersonType;
注意这个和结构体在定义的时候直接初始化一个值的区别,这个是由typedef关键字的,且是别名,而不是一个变量。
/
typedef struct {
int age;
char *name;
} PersonType;
省略结构体名。
/
// typedef和指向结构体的指针
// 首先定义一个结构体并起别名
typedef struct { float x; float y; } Point;
// 起别名
typedef Point *PP;
与枚举的声明定义一样,在对枚举使用typedef时,也有三种形式:
enum Sex{
SexMan,
SexWoman,
SexOther
};
typedef enum Sex SexType;
/
typedef enum Sex{
SexMan,
SexWoman,
SexOther
} SexType;
/
typedef enum{
SexMan,
SexWoman,
SexOther
} SexType;
typedef和函数指针:(重要!)
int add(int a, int b) {
return a + b;
}
int main() {
typedef int (*myFunction) (int, int);
//注意此时myFunction就是int (*myFunction) (int, int)的别名。表示这是一种指向函数的指针的类型。
myFunction p = add;
p();
return 0;
}