-3

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.

ravi
  • 10,994
  • 1
  • 18
  • 36

3 Answers3

1

Attempting to modify a const object causes undefined behaviour.

You cannot "remove the constness" of a const object.

In this case, your compiler is being nice to you by generating an exception, instead of just behaving weirdly and continuing.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • It's not the compiler, that generates the exception, but rather the OS that protects itself against a write attempt to read-only memory. – IInspectable Jan 09 '17 at 14:41
1

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 as const, and only use const_cast to regain write access to variable that was initially defined as non-const.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • @ravi: it doesn't help anyone to claim it's not entirely true without providing details... when specifically do you believe it's allowed? I've looked quite closely over the Standard and it seems to be explicitly undefined behaviour in all the imaginable edge cases of local variables, even writing over `new const int(n)`.... Cheers. – Tony Delroy Nov 25 '14 at 14:08
  • Small correction: The distinction should be between objects with static storage duration, and objects with automatic/dynamic storage duration. Global variables have static storage duration just like function-local `static` objects. – IInspectable Jan 09 '17 at 14:43
0

Casting away an original const and attempting a modification is Undefined Behavior.

You are not guaranteed to get an exception, but your are lucky to get one.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331