类型定义符 typedef

目录

1,typedef——起别名

2,typedef 数组

3,typedef 和 结构体(数组)

4,typedef 和 宏

5,typedef 函数指针


1,typedef——起别名

typedef int INTEGER
INTEGER a,b;
它等效于:
int a,b;

2,typedef 数组

typedef char NAME[20];
NAME a1,a2,s1,s2;
完全等效于:
char a1[20],a2[20],s1[20],s2[20]

3,typedef 和 结构体(数组)

示例:

typedef struct struc
{
    int a;
    int b;
}stru,stru2[3];

int main()
{
    stru s1;
    stru2 s2;
    s1.a=1,s2[0].b=2;
    cout<<s1.a+s2[0].b;
    return 0;
}

注意区分不用typedef的普通写法:

struct struc
{
    int a;
    int b;
}stru,stru2[3];

int main()
{
    stru.a=1,stru2[0].b=2;
    cout<<stru.a+stru2[0].b;
    return 0;
}

两个程序的逻辑一样,输出结果都是3

扫描二维码关注公众号,回复: 8690612 查看本文章

4,typedef 和 宏

有时也可用宏定义来代替 typedef 的功能:

typedef 原类型名 新类型名

#define 新类型名 原类型名

但是宏定义是由预处理完成的,而 typedef则是在编译时完成的,而且typedef的带数组的用法是不能用宏替代的。

5,typedef 函数指针

示例:

typedef char (*func)(int);

char GetChar(int a)
{
    return '0' + a%10;
}

int main()
{
    func f=GetChar;
    cout<<f(5);
    return 0;
}

输出:

5

发布了1185 篇原创文章 · 获赞 679 · 访问量 171万+

猜你喜欢

转载自blog.csdn.net/nameofcsdn/article/details/103936770
今日推荐