typedef说明

typedef 只对已有的类型进行别名定义,不产生新的类型;

#define 只是在预处理过程对代码进行简单的替换。

类比理解:

typedef  unsigned int  UINT32;  // UINT32 类型是unsigned int

UINT32 sum;                                 // 定义一个变量:int sum;

 

typedef  int  arr[3];                     // arr 类型是 int[3];(存放int型数据的数组)

arr a;                                              // 定义一个数组:int a[3];

 

同理:

typedef  void (*pfun)(void);         // pfun 类型是 void(*)(void)

pfun main;                                       // 定义一个函数:void (*main)(void);

 

在博客上看到一个经典的函数指针用例:

为保护原创作者的权益,以下例子代码不作修改:

<来源网址:http://www.cnblogs.com/shenlian/archive/2011/05/21/2053149.html>

#include<stdio.h>

typedef int (*FP_CALC)(int, int);

-----------------------------------------------------------------------------------------------------------------------------------------
其实就是函数指针的用法
下面这篇文章讲的很详细
http://blog.csdn.net/qll125596718/article/details/6891881
#include<stdio.h>
typedef void (*fun)(void) ;
char (*pFun)(int);
char glFun(int a)
{
    return char(a);
}
int main()
{
    pFun = glFun;
    printf("%c\n",(*pFun)(2));
    printf("%c\n",pFun(2));
    return 0;
}

第一行定义了一个指针变量pFun。首先我们根据前面提到的“形式1”认识到它是一个指向某种函数的指针,这种函数参数是一个int型,返回值是char类型。只有第一句我们还无法使用这个指针,因为我们还未对它进行赋值。

第二行定义了一个函数glFun()。该函数正好是一个以int为参数返回char的函数。我们要从指针的层次上理解函数——函数的函数名实际上就是一个指针,函数名指向该函数的代码在内存中的首地址

然后就是main()函数了,它的第一句您应该看得懂了——它将函数glFun的地址赋值给变量pFun。main()函数的第二句中“*pFun”显然是取pFun所指向地址的内容,当然也就是取出了函数glFun()的内容,然后给定参数为2。

 



 

在c语言中,定义一个结构体要用typedef ,例如下面的示例代码,Stack sq;中的Stack就是struct Stack的别名。

如果没有用到typedef,例如定义

struct test1{
int a;
int b;
int c;

};

test1 t;//声明变量

下面语句就会报错

struct.c:31:1: error: must use 'struct' tag to refer to type 'test1'

test1 t;

^

struct 

1 error generated.

声明变量时候就要用struct test1;这样就解决了

 

如果这样定义的话

typedef struct test3{
int a;
int b;
int c;
}test4;

test3 d;
test4 f;

此时会报错

struct.c:50:1: error: must use 'struct' tag to refer to type 'test3'

test3 d;

^

struct 

1 error generated.

所以要struct test3这样来声明变量d;

 

分析一下:

上面的test3是标识符,test4 是变量类型(相当于(int,char等))。

 

 我们可以用struct test3 d来定义变量d;为什么不能用test3 d来定义是错误的,因为test3相当于标识符,不是一个结构体,struc test3 合在一起才代表是一个结构类型。

所以声明时候要test3时候要用struct test3 d;

 

typedef其实是为这个结构体起了一个新的名字,test4;

typedef struct test3 test4;

test4 相当于struct test3;

就是这么回事。

 

posted @ 2018-03-16 17:11  banluxinshou  阅读(223)  评论(0编辑  收藏  举报