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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章