g*******n 发帖数: 86 | 1 void f()
{
const int i=9;
......;
cout<
}
-1
问中间的......怎样写能输出-1这结果。我一开始说用const_cast,他说还有其他方
法吗,最后告诉我建立int arr[10],修改
arr[-1]的值就能间接修改i的值。我当时称赞他的方法很妙。回来后试验了一下发现都
不是这么回事。第一,const_cast不
能改变被修改的变量的属性,就是说不能去掉i的const属性;第二,他说的方法也不
可行,我建立一个数组它-1项的地
址根本不是i,如果我强制让它指向i并修改,cout时i还是9。
这确实是个边边角角的钻牛角尖问题。不过我我还是很想知道答案,对compiler比较熟
悉的同学谁能给点hint? |
f*****w 发帖数: 2602 | 2 要我被问到多半只会回答可以建一个pipe 把cout 重定向掉... |
g*********s 发帖数: 1782 | 3 i think it's about where to allocate constant defined in a C++ function.
i don't remember the details. but my bet is it's also in static segment,
which can explain why a[-1] doesn't help.
on the other hand, i think const_cast can remove constness.
【在 g*******n 的大作中提到】 : void f() : { : const int i=9; : ......; : cout<: } : -1 : 问中间的......怎样写能输出-1这结果。我一开始说用const_cast,他说还有其他方 : 法吗,最后告诉我建立int arr[10],修改 : arr[-1]的值就能间接修改i的值。我当时称赞他的方法很妙。回来后试验了一下发现都
|
a*******8 发帖数: 2299 | |
r*******y 发帖数: 1081 | 5 It works. But why this works?
【在 a*******8 的大作中提到】 : #define i -1
|
s*z 发帖数: 37 | 6 wonder if this works...
void f() {
const int i=9;
cout << -1;
return
cout << i;
}
【在 g*******n 的大作中提到】 : void f() : { : const int i=9; : ......; : cout<: } : -1 : 问中间的......怎样写能输出-1这结果。我一开始说用const_cast,他说还有其他方 : 法吗,最后告诉我建立int arr[10],修改 : arr[-1]的值就能间接修改i的值。我当时称赞他的方法很妙。回来后试验了一下发现都
|
l*****a 发帖数: 559 | 7 try this one
#include
#include
#include
using namespace std;
int main(){
const volatile int i = 10;
volatile const int* tmp = &i;
int* j = const_cast (&i);
*j = 2;
cout<
system("PAUSE");
return 0;
}
the compiler optimization cached i and hid the i's value after the change.
to tell the truth, i do hate bloomberg asking this kind of silly question. |
d*********t 发帖数: 33 | 8 haha 这个给力 work的话把考官气晕
【在 s*z 的大作中提到】 : wonder if this works... : void f() { : const int i=9; : cout << -1; : return : cout << i; : }
|
D***n 发帖数: 149 | 9 哈哈,这们仁兄太有才了...
haha 这个给力 work的话把考官气晕
【在 s*z 的大作中提到】 : wonder if this works... : void f() { : const int i=9; : cout << -1; : return : cout << i; : }
|