天天看点

C语言:用typedef定义结构普通定义结构的方法使用typedef定义结构typedef定义普通变量类型名

普通定义结构的方法

//定义结构Date1
struct Date1
{
    int year;   //年
    int mouth; //月
    int day;  //日
};

int main()
{
    struct Date1 birth1={2002,6,28};                           //声明Date1类型的结构变量birth1,同时赋值
    printf("某个漂亮小姐姐的生日是%d年%d月%d日\n",birth1.year,birth1.mouth,birth1.day);//打印结构变量birth2
    return 0;
}
           

输出结果:

C语言:用typedef定义结构普通定义结构的方法使用typedef定义结构typedef定义普通变量类型名

那每次要声明结构Date1类型的变量,都要写struct Date1 …(变量名)…,岂不是好烦?

使用typedef定义结构

使用typedef定义结构,会让声明语句变得简洁,请看下面的代码:

#include <stdio.h>
//定义Date2结构类型,用DATE作为结构变量声明语句
typedef struct Date2
{
    int year;   //年
    int mouth; //月
    int day;  //日
}DATE;

int main()
{
    DATE birth2={2001,6,17};                                 //用代号DATE声明Date2结构变量birth2
    printf("噢~记错了是%d年%d月%d日\n",birth2.year,birth2.mouth,birth2.day);//打印结构变量birth2
    return 0;
}
           

输出结果:

C语言:用typedef定义结构普通定义结构的方法使用typedef定义结构typedef定义普通变量类型名

那么每次声明Date系列结构变量,struct Date1就换成了DATE,是不是方便多了(如果声明语句使用次数很多的话)。同时,这么一来Date2就变得“徒有其名”了,以后的声明完全用不上。那就没必要“浪得虚名”了,可以省略掉。不过最好在附近打上注释,否则自己都忘了,这个结构干啥用的。

#include <stdio.h>
//定义Date2结构类型,用DATE作为结构变量声明语句
typedef struct
{
    int year;   //年
    int mouth; //月
    int day;  //日
}DATE;

int main()
{
    DATE birth2={2001,6,17};                                 //用代号DATE声明Date2结构变量birth2
    printf("噢~记错了是%d年%d月%d日\n",birth2.year,birth2.mouth,birth2.day);//打印结构变量birth2
    return 0;
}

           

输出结果(跟上面一模一样):

C语言:用typedef定义结构普通定义结构的方法使用typedef定义结构typedef定义普通变量类型名

希望以后师妹不要学C语言,不然我记错她的生日怕是会被打死。typedef的用法并没有那么肤浅。还可以用来定义自己喜欢的变量类型名。

typedef定义普通变量类型名

上代码块:

#include <stdio.h>
typedef int YEAR   ;//以后就可以用YEAR来声明整型(int)变量了
typedef float SCORE;// 以后就可以用SCORE来声明单精度浮点型型(float)变量了

int main()
{
    YEAR y=2020;
    SCORE s=150;
    printf("祝师妹%d高考,科科%.0f,旗开得胜!Yeah!",y,s);
    return 0;
}
           

输出结果:

C语言:用typedef定义结构普通定义结构的方法使用typedef定义结构typedef定义普通变量类型名

继续阅读