using const_cast (need explanation)

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main() {
    const int a = 2;
    const int& b = a;
    const_cast<int&>(b) = 3;
    cout << b << endl << a;
    return 0;
}


hello,
is there any chance to change the value of variable a as it is now?
I know it's possible if a is used as pointer, but I wanna change it like it is now in this example, how would I go to do that?

thanks in clarification.
LOL, sorry for double posting...
I've just found a way to do that:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main() {
    volatile const int a = 2;
    const_cast<int&>(a) = 3;
    cout << a; //LOL now a is 3 instead of 2
    return 0;
}


very simple :)
how would I go to do that?


get rid of the 'const' in front of a.

Seriously. The whole point behind "const" is that it means "can't be modified". If you're trying to modify it, it shouldn't be const.

Don't try to do clever casts around it.
Last edited on
Topic archived. No new replies allowed.