首页 > 其他 > 详细

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

时间:2021-04-08 01:35:30      阅读:38      评论:0      收藏:0      [点我收藏+]

当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 小知识点(二): 修改const修饰的变量会怎样?

原文:https://www.cnblogs.com/yinheyi/p/14630124.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!