[C]typedef实例

一、概述

1.是声明一个长声明的缩写

typedef是声明一个同义字,所以:

typedef unsigned int U4;
U4 foo = 512;

等价于:

unsigned int foo = 512;

2.是预处理指令

因为是预处理指令,所以在小标签被定义之前typedef也是被允许的:

typedef struct Horse MyHorse;
struct Horse
{
    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];
};

3.相对小标签具有不同的命名空间

typedef的同义词与结构标签,声明小标签,三者都具有不同的命名空间,所以在这里三者同名也是被允许的:

#include <stdio.h>
typedef struct Horse Horse;
struct Horse
{
    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];
};
int main(void)
{
    Horse Horse = {11, 180, "Lucy", "Alex", "Michell"};
    printf("%s\n", Horse.name);
    return 0;
}

 4.一定要有一个标签名

typedef声明一个类型时,一定要给定一个标签名作为同义词:

//此标签名为FOO,标签类型是指针,所以它适合用于描述指针
typedef char* (*FOO)(char* s);
//声明一个这样类型的指针
FOO ptr = NULL;

 

 

二、实例

1.函数指针类型声明

#include <stdio.h>
typedef char* (*FOO)(char* s);//声明一个指针类型,指向一个返回char*,参数为char*的函数
char* BAR(char* s){
    return s;
}
int main(void)
{
    FOO arr[] = {BAR};
    char str[] = "Hello world.";
    printf("%s\n", arr[0](str));
    return 0;
}

其中

typedef char* (*FOO)(char* s);
FOO arr[] = {BAR};

此声明等价于:

char* (*arr[])(char* s) = {BAR};

 

posted @ 2020-09-15 10:53  yiyide266  阅读(254)  评论(0编辑  收藏  举报