typedef 关键字

来源:互联网 发布:套号学历淘宝被骗 编辑:程序博客网 时间:2024/06/01 10:00

typedef  为C语言的关键字,其作用是为了一种数据类型(包括内部数据类型 int , char 等和自定义的数据类型 struct 等)定义一个新的名字。即是说,同一种数据类型有两个名字表示,并不是说定义了新名字,原来的数据类型名就不能用。

使用typedef 的目的有两个:一是给变量一个易记且意义明确的新名字;二是简化一些比较复杂的类型声明。


(1)typedef 的最简单使用

typedef  long  byte_4;

    给已知的数据类型起了一个新名字,叫 byte_4。使用long 和byte_4 都可以定义long 这种数据类型。

 例如:

  long   num;

或是

   byte_4  num;

都表示定义了变量num的数据类型为long。    


(2)typedef 与结构struct 结合使用,有三种方法可用

方法一:

typedef  struct student_score

{

    char name[20];

    int  stu_num;

    int   score;

} Score;


方法二(这种方法c语言编译器是支持的)

typedef struct student_score  Score;

struct student_score 

{ 

    char name[20];

    int  stu_num;

    int   score;

};       //用typedef 给一个还没有完全声明的类型起新名字。


方法三:

struct student_score 

{ 

    char name[20];

    int  stu_num;

    int   score;

};

typedef struct student_score  Score;


这三个方法都是在给自定义的数据类型struct student_score 重新起一个名字 Score。


typedef 与define 的区别:

define知识简单的字符串替换,而typedef 是重新起了一个名字。 



0 0