ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

const 小知识点(二): 修改const修饰的变量会怎样?

2021-04-07 23:34:36  阅读:266  来源: 互联网

标签:知识点 const int double namespace 修饰 10.5 include


当const修饰全局变量时,修改它会怎么样?

看如下代码:

  1 #include <iostream>
  2 using namespace std;
  3 
  4 const double a = 10.5;
  5 
  6 int main() {
  7     double* p = const_cast<double*>(&a);
  8     *p = 110.5;
  9     return 0;
 10 }

编译可过,运行时,段错误。

原因是全局的const变量分配到了只读内存区。可以写如下代码验证一下:

  1 #include <iostream>
  2 using namespace std;
  3 
  4 const int a = 10.5;
  5 const int b = 10.5;
  6 
  7 int c = 100;
  8 int d = 100;
  9 
 10 int main() {
 11     cout << &a << endl;
 12     cout << &b << endl;
 13     cout << &c << endl;
 14     cout << &d << endl;
 15     return 0;
 16 }

输出内容如下所示。内存地址差了很多的。

当const修饰局部变量时,修改它会怎么样?

代码如下:


  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main() {
  5     const double a = 10.5;
  6     double* p = const_cast<double*>(&a);
  7     *p = 20.5;
  8     cout << a << endl;
  9     cout << *p << endl;
 10     return 0;
 11 }

编译后,输出如下图:

输出符合你的预期没? 继续执行下面代码:

 1 #include <iostream>
  2 using namespace std;
  3 
  4 int main() {
  5     volatile const double a = 10.5;
  6     double* p = const_cast<double*>(&a);
  7     *p = 20.5;
  8     cout << a << endl;
  9     cout << *p << endl;
 10     return 0;
 11 }

编译后,输出为如下图:

原因:编译器对const变量进行了优化,读取它的值时,直接从寄存器里拿。当加上volatile修饰后,编译器指示每次从内存中读取。

标签:知识点,const,int,double,namespace,修饰,10.5,include
来源: https://www.cnblogs.com/yinheyi/p/14630124.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有