码迷,mamicode.com
首页 > 其他好文 > 详细

typedef和define的一些区别

时间:2015-06-20 19:40:40      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:define   const   typedef   

#include <stdio.h>

#define PINT int*
typedef int* pint;


/*以下实验说明了:
(1)typedef int* pint;
    const pint p1=&i1  
    的效果是和下面的一样的
    int* const p1;
    这里的const锁住的是(p1),所以p1=&i2都是错的,因为这里内存地址p1已经被const锁住,而*p1=其他值是可以的
(2#define  PINT int*
    const PINT p2=&i1
    的效果是和下面的一样的
    const int *p2;
    这里const 锁住的是(*p2);所以*p2赋予其他值是错误的,因为这里值已经被锁住,而内存地址p2是可以赋予其他地址的。

(3)pint a,b的效果和int* a;int* b;相同
    PINT a,b的效果和int* a;int b相同
(4)typedef int* pint;
    pint const  p1=&i1;
    的效果和(1)是一样的;
(5#define  PINT int*
    PINT const p2=&i1;
    的效果与(2)刚好相反,也与(1)相同。


    总结:由此可见,
    (1)defined是宏替换,所以替换在编译之前,如const PINT p2=&i1,PINT const p2=&i1;进行了替换后在编译的话,编译的时候就会让编译器直接
    看到const int *p2以及int* const p2;
    (2)而关键字typedef有种助记符的赶脚,所以在编译的时候反应比const慢,所以放在哪里都是先识别const先,变成int* const p1。
    (3)嘻嘻,其他差异也可以看看说明的(3)

*/

void main()
{
    int i1=30;
    int i2=40;
    //const int *p=&i1;
    const int *p;
    p=&i1;
    p=&i2;  //此处,p可以在任何时候重新赋值一个新的内存地址。
    i2=80;  //这里能用*p=80来代替吗?答案是不能
    //*p=30;
    i1=35;

    //const pint p1=&i1;
    pint const p1=&i1;
    //const PINT p2=&i1;
    //PINT const p2=&i1;
    //int* const p3=&i1;
    //i1=40;
    //p2=&i2;
    //*p1=50;
    //*p2=89;
    //p1=&i2;
    //*p3=
    //i2=90;

//    printf("%d",*p2);  //输出80
}

typedef和define的一些区别

标签:define   const   typedef   

原文地址:http://blog.csdn.net/u011446963/article/details/46575029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!