Below is the code :-
const int temp=100;
class A
{
public:
void fun(int& temp)
{
cout<<"am inside fun()"<<endl;
temp = 2000; <<<<<<<<<<<<<<Here getting exception....
printf("in fun() temp[%p] temp val[%d]\n",&temp, temp);
}
};
int main()
{
A a;
printf("in main() temp[%p] temp val[%d]\n",&temp, temp);
a.fun(const_cast<int&>(temp));
cout<<"temp:"<<temp<<endl;
system("pause");
return 0;
}
In this case it's not allowing me to overwrite temp in fun even when I explicitly removed the constness. When I declare temp inside main everything is fine i.e it allows me to overwrite that value in fun.
Compiled in VS2008.
Can anyone help me figure out the behavioral difference between these two scenarios.
The difference is that the global variable's likely to be located in a read-only memory segment, so attempts to modify it will may be trapped by the CPU, while a local non-
static
const variable's likely to be put in a CPU register or on the stack where it's possible to modify it. That said, you should avoid changing variables defined asconst
, and only useconst_cast
to regain write access to variable that was initially defined as non-const
.