C语音基础-typedef 24

来源:互联网 发布:萤石软件下载 编辑:程序博客网 时间:2024/06/07 00:06

 1. typedef ----> type define  类型定义.

 

    作用:为一个已经存在的数据类型取1个别名.

   

    语法格式:

 

    typedef 已经存在的数据类型别名;`

 

    typedef char* string;

    char* 类型取1个别名.叫做string

 

    所以,就可以使用string代替char*

    size_t  其实就是 unsigned long

 

 

 

 2. 什么时候为已经存在的数据类型取1个别名呢?

 

 

    当数据类型很长的时候,就可以为这个数据类型取1个短1点的别名.

    这样用起来就很方便.

    

 3. 使用typedef为结构体类型取别名.

 

    1).先声明结构体类型.然后在使用typedef为这个结构体类型取1个短别名.

 

         struct Student

         {

            char *name;

            int age;

            int score;

         };

         typedef struct Student Student;

 

    2).声明结构体类型的同时,就使用typedef来为结构体类型取1个短别名.

 

         typedef struct Student

         {

             char *name;

             int age;

             int score;

         } Student;

 

 

    3).声明匿名结构体的同时,就使用typedef来为结构体类型取1个短别名.

 

         typedef struct

         {

             char *name;

             int age;

             int score;

         } Student;

 

         这是最常用的方式.

 

4. 使用typedef为枚举类型取1个短别名

 

    1).先声明枚举类型,然后再使用typedef来为枚举类型取1个短别名.

 

 

         enum Direction

         {

             DirectionEast,

             DirectionSouth,

             DirectionWest,

             DirectionNorth

         };

         

         typedef enum Direction Direction;

 

 

    2).声明枚举类型的同时,就使用typedef来为枚举体类型取1个短别名

    

         typedef enum Direction

         {

             DirectionEast,

             DirectionSouth,

             DirectionWest,

             DirectionNorth

         } Direction;

 

 

    3).使用上面这种方式的时候,枚举的名称就没有必要写了.

 

         typedef enum

         {

             DirectionEast,

             DirectionSouth,

             DirectionWest,

             DirectionNorth

         } Direction;

原创粉丝点击