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

时间:2021-04-08 13:49:55   收藏: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修饰后,编译器指示每次从内存中读取。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!