zoukankan      html  css  js  c++  java
  • 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。。。。。。。
        }
    
    }
  • 相关阅读:
    lambda表达式
    You can't specify target table 't_mail_marketing' for update in FROM clause
    从对象list中获取对象属性list
    枚举缓存
    Solr语法
    通过Telnet查询注册服务
    日志查询
    Maven 屏蔽静态文件
    抽奖
    随机码生成方法
  • 原文地址:https://www.cnblogs.com/bwbfight/p/11299511.html
Copyright © 2011-2022 走看看