1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <bits/stdc++.h>
int main() { std::ios::sync_with_stdio(false); std::cin.tie(0);
const int a = 1; int *p = const_cast<int *>(&a); ++(*p); std::cout << a << std::endl; std::cout << *(&a) << std::endl; std::cout << *p << std::endl;
return 0; }
|
输出:
在const int a = 1前面加上volatile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <bits/stdc++.h>
int main() { std::ios::sync_with_stdio(false); std::cin.tie(0);
volatile const int a = 1; int *p = const_cast<int *>(&a); ++(*p); std::cout << a << std::endl; std::cout << *(&a) << std::endl; std::cout << *p << std::endl;
return 0; }
|
输出:
内存中的a被修改为2,但寄存器中a的值仍然为1,volatile关键字告诉编译器从内存中读取,因此出现了不同的现象。