typedef
c 语言支持一种typedef的机制,它允许你为各种数据制定新的名字。
例如 把ptr_to_char声明为一个指向字符的指针
typedef ptr_to_char *char
//声明a是一个指向字符的指针
ptr_to_char a;
define
进行简单的替换工作
#define MAX_NUM 10
int i = 0;
for(i=0; i< MAX_NUM; i++){
printf(" count %d\n", i);
}
他们的区别
类型不同
typdef 是关键字, define是预处理指令
处理阶段不同
typedef是在编译阶段处理,并且具有类型检查功能。
define 是在预处理阶段进行简单替换。
功能不同
typedef 通常用于类型定义。
define 用于变量定义 宏开关 常量。
对指针的操作也不同
typedef int * pint;
#define PINT int *
int i1 = 1, i2 = 2;
const pint p1 = &i1; //p不可更改,p指向的内容可以更改,相当于 int * 7 const p;
const PINT p2 = &i2; //p可以更改,p指向的内容不能更改,相当于 const int *p;或 int const *p;
pint s1, s2; //s1和s2都是int型指针
PINT s3, s4; //相当于int * s3,s4;只有一个是指针。
void TestPointer()
{
cout << "p1:" << p1 << " *p1:" << *p1 << endl;
//p1 = &i2; //error C3892: 'p1' : you cannot assign to a variable that is const
*p1 = 5;
cout << "p1:" << p1 << " *p1:" << *p1 << endl;
cout << "p2:" << p2 << " *p2:" << *p2 << endl;
//*p2 = 10; //error C3892: 'p2' : you cannot assign to a variable that is const
p2 = &i1;
cout << "p2:" << p2 << " *p2:" << *p2 << endl;
}

1524

被折叠的 条评论
为什么被折叠?



