Is const_cast safer than normal cast?

c++

Solution

It's safer in the sense that you won't get a cast that's something other than just removing `const`:

int main()
{
    const char i=5;
    int *ptr;
    ptr=(int*)&i;  // the compiler won't complain

    ptr=const_cast<int*>(&i); // will fail, since `i` isn't an int
    return 0;
}

which doesn't necessary mean that the `const_cast<>` is safe:

const int i=5;

int main()
{
    int const& cri(i);

    int& ri = const_cast<int&>(cri);  // unsafe

    ri = 0; // will likely crash;

    return 0;
}

Problem

Which is safer to use? ``` int main() { const int i=5; int *ptr; ptr=(int*)&i; <------------------- first ptr=const_cast<int*>(&i); <-------------------Second return 0; } ```

Original source

Related problems