typedef的小心得

在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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值