常量折叠解析

1.1 系统内置类型

#include<iostream>
using namespace std;

int main()
{
	const int test = 10;
	int* p = const_cast<int*>(&test);
	*p = 20;
	cout << "test的地址为:" << &test << "  test的值为:" << test << endl;;
	cout << "p的地址为:" << p << "  p的值为:" << *p;
	system("pause");
	return 0;
}

test的地址为:009AFA44 test的值为:10
p的地址为: 009AFA44 p的值为:20

1.2 用户自定义类型

int main(void)
{	
	struct TT
	{
		int a;
		int b;
	};
	const TT s = {1,2};
	cout << "[s]:" << s.a <<","<<s.b << endl;	//输出 1,2
	TT *result = const_cast<TT *>(&s);
	result->a = 10;	
	result->b = 20;
 
 
	cout << "[s]:" << s.a <<","<<s.b << endl;//输出 10,20
	cout << "[r]:" << result->a <<","<<result->b << endl;//输出 10,20
	getchar();
 
	return 0;
}
[s]:1,2
[s]:10,20
[r]: 10,20

对于常量折叠这种编译器预处理,只对内置类型有效,对于自定义类型就没有效果。

1.3 问题

#include<iostream>
using namespace std;

int main()
{
	int i = 10;
	const int test = i;
	int* p = const_cast<int*> (&test);
	*p = 24;
	cout << "i的地址是:" << &i << " i的值是:" << i << endl;
	cout << "p的地址是:" << p << " p的值是:" << *p << endl;
	cout << "test的地址是:" << &test << " test的值是:" << test<<endl;
}
i的地址是:003AF808 i的值是:10
p的地址是:003AF7FC p的值是:24
test的地址是:003AF7FC test的值是:24
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值