2

In the following code:

    #include<iostream>
    using namespace std;
    int main()
    {
        const int i = 8;
        int j = 90;
        const_cast<int &>(i)  = 10;
        static_cast<const int&> (j);
        j = 200;
        cout << " i = " << i << endl;
        cout << " j = " << j << endl;
   }

I thought the output will be

i = 10
j = 90

But the actual output was

i = 8
j = 200 

So the casting did not work ?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
parusha
  • 53
  • 4
  • I recommend the excellent documentation at [https://en.cppreference.com](https://en.cppreference.com) for a first approach. Only if you cannot find an answer there, ask here. In this case, you would have found [this](https://en.cppreference.com/w/cpp/language/const_cast) ... – Walter Oct 11 '18 at 09:12
  • @StoryTeller: Nice duplicate for future research purposes. I've change the title; to me this one is well-asked and could be helpful in future searches. – Bathsheba Oct 11 '18 at 09:29
  • 1
    @Bathsheba - I'm always for good signposts. You won't believe how lost I got whilst on a trip in the country recently... – StoryTeller - Unslander Monica Oct 11 '18 at 09:54

1 Answers1

7

The behaviour of const_cast<int &>(i) = 10; is undefined. That's because i is originally const and you are casting away the const-ness and attempting to write to the object. So any output could be observed.

static_cast<const int&> (j); is a no-op: it doesn't somehow transform j into a const type. The subsequent j = 200; is a trivial assignment

Bathsheba
  • 231,907
  • 34
  • 361
  • 483