c++中const和c中const区别

#include <algorithm>
#include <iostream>
#include <functional>
#include <vector>
#include <numeric>
#include <array>
#include <cstring>
#include <cstdio>
#include <functional>//包装头文件
using namespace  std;
#if 0
//在C语言中
int main()
{
    const int num = 100;
    //int a[num];//错误,num其实是个伪常量
    *(int*)&num = 4;
    printf("%d",num);//4,C语言,const不是真正意义上的常量,只能避免直接修改,无法避免间接修改
    getchar();
}
#endif
//在c++中
int main1()
{
    //const int n = 20;
    //int a[n];//可以,因为c++编译器会做自动优化,发现n的地方都会直接替换成10,而不去内存中取
    
    int a = 10;
    const int n = a;//const仍然是伪常量,但是只是c++编译器会做优化,但是这儿是变量,
    int data[n];//不可以.c++编译器不敢乱优化,因为变量可能发生变化

}
void main3()
{
    const int num= 20;
    *(int*)(&num) = 3;
    cout << *(&num)<< endl;//优化,强行替换,不从内存中取,而直接从寄存器取20
    cout << num << endl;//20

}


void main4()
{
    int  a = 10;
    const int num = a;//不敢直接优化
    *(int*)(&num) = 3;
    cout << *(&num) << endl;//直接从内存中取10,变量不敢直接优化
    cout << num << endl;

}

void main()
{
    const int num[5]{1, 2, 3, 4, 5};
    const int *p = num;
    *(int*)p = 100;//但是*p=10,指向常量的指针,不能修改
    //const 数值没有优化,可以间接改变
    for (auto i:num)
    {
        cout << i << endl;//100。。。。。。。
    }

}

 

原文链接: https://www.cnblogs.com/bwbfight/p/11299511.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++中const和c中const区别

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300279

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午9:18
下一篇 2023年2月15日 下午9:19

相关推荐