typedef 和 #define

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;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值