typedef的小心得

来源:互联网 发布:搜狐网络大厦 邮编 编辑:程序博客网 时间:2024/05/01 07:52

在C中,typedef可以说无处不在,本文简单介绍一下typedef的两种用法:

一:用于各种类型或结构体的替代(特别是结构体):

1、用于基本数据类型的别名定义:

# include <stdio.h>

typedef int a;

int main()
{
    a aa = 1;
    printf("the aa is %d\n",aa);
    return 0;
}

结果为:the aa is 1

2、用于结构体定义的简化

如果不用typedef的话,结构体便必须带有struct,这会造成定义或引用结构体变量时带来很大的不便,故一般都用typedef来简化结构体变量的定义和声明。

# include <stdio.h>


typedef struct
{
    int ID;
    int age;
}stu; //将结构体直接定义为stu,以后stu便时结构体struct{int ID; int age}


int main()
{
    stu aa = { 1,12 };//对结构体aa进行赋予初值
    stu bb[2] = {{2,13},{3,14}};//对结构体数组进行初值赋予
    printf("the aa.ID is %d,the aa.age is %d\n",aa.ID,aa.age);
    for(int i=0;i<2;i++){
        printf("the bb[%d].ID is %d,the bb[%d].age is %d\n",i,bb[i].ID,i,bb[i].age);
    }
    return 0;
}

结果:

the aa.ID is 1,the aa.age is 12
the bb[0].ID is 2,the bb[0].age is 13
the bb[1].ID is 3,the bb[1].age is 14

二、用于函数指针的别名定义

形式:typedef  返回类型 (*别名)(形参)

# include <stdio.h>

typedef int (*add)(int a,int b);
int aa(int a,int b)
{
    return (a+b);
}

int main()
{
    add bb;
    bb = aa;
    printf("the return value of the bb is %d\n", bb(1,2));
    return 0;
}


结果为:the return value of the bb is 3


参考了博客:http://www.cnblogs.com/shenlian/archive/2011/05/21/2053149.html



原创粉丝点击