c中的const与c++中的const

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18509807/article/details/72465678

c中的const是一个伪只读标识符。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    const int a = 10;
    int *p = &a;
    *p = 20;
    printf("%d\n",a);
    return 0;
}

此时输出a的值为20,被指针间接的改变了。


c++中,const进行了增强,不在是一个伪标识符了。

const int a = 10;
int *p = (int *)&a;
    *p = 20;
    cout << a << *p << endl;
    cout << &a << endl;
    cout<< p;

输出:
a :10;
*p :20;
两者的地址是一样的。
那么问题来了,既然两者所指向的地址是一样的,那为什么内容不一样呢?请继续往下看。
c++编译器引入了一个符号表,当碰见常量声明时,在符号表中存放常量,那么如何解释取地址呢?
编译过程中若发现使用常量则直接以符号表中的值替换编,译过程中若发现对const使用了extern或者&操作符,则给对应的常量分配存储空间。
结论
C语言中的const变量
C语言中const变量是只读变量,有自己的存储空间
C++中的const常量
可能分配存储空间,也可能不分配存储空间
当const常量为全局,并且需要在其它文件中使用
当使用&操作符取const常量的地址

联想 const和#define的区别
对比加深
C++中的const常量类似于宏定义
const int c = 5; ≈ #define c 5
C++中的const常量在与宏定义不同
const常量是由编译器处理的,提供类型检查和作用域检查
宏定义由预处理器处理,单纯的文本替换

void fun1()
{
    #define a 10
    const int b = 20;
    //#undef
}

void fun2()
{
    printf("a = %d\n", a);
    //printf("b = %d\n", b);
}

int main(int argc, char *argv[])
{
    fun1();
    fun2();
    return 0;
}

a 可以在fun2中使用,而b不能在fun2中使用,说明const提供了类型和作用域的检测。

猜你喜欢

转载自blog.csdn.net/qq_18509807/article/details/72465678