define和typedef有两个主要的区别:
(1)可以使用其他类型说明符对宏类型名进行扩展,但是对typedef所定义的类型名不能扩展
(2)在连续的几个变量的声明中,用typedef定义的类型可以保证声明中所有的变量均为同一种类型,但是define无法保证
具体的两个区别如下:
#include <stdio.h>
int main()
{
#define define_int_ptr int *
typedef int * typedef_int_ptr;
// first diff
unsigned define_int_ptr i;
typedef_int_ptr j;
unsigned typedef_int_ptr k;
// second diff
define_int_ptr a, b, c;
typedef_int_ptr d, e;
a = NULL;
b = NULL;
c = 0;
d = NULL;
e = NULL;
return 0;
}
编译结果如下:
test.c: In function ‘main’:
test.c:11: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘k’
test.c:11: error: ‘k’ undeclared (first use in this function)
test.c:11: error: (Each undeclared identifier is reported only once
test.c:11: error: for each function it appears in.)
test.c:18: warning: assignment makes integer from pointer without a cast
第11行编译出错,而9,10是ok的,这个验证了了区别(1)
第18行类型转换警告,而19没有警告,说明类型是int型,这个验证了区别(2)