1

I see this post which explain the const_cast<> and says it is beneficial when pointers/references are used. However, consider the following codes:

1-

const_cast<SCOTCH_Num*>(xadj) 

which I get invalid const_cast from type 'cost label* {aka const long int *}' to type 'SCOTCH_Num* {aka int*}'. So, pointers are casted. Isn't that?

and

2-

(SCOTCH_Num*)(xadj) 

which I get warning: use of old-style cast [-Wold-style-cast]

You may ask about the variable definitions, but the aka part in the error is clear. If I have propose more details, please let me know.

5
  • There is no thing as a const_cast in C. Therefore, I think you talk about C++. Commented Feb 5, 2018 at 13:39
  • Beneficial may not be the right word. It's the only case where it has any use, but there's no benefits. Commented Feb 5, 2018 at 13:42
  • Beyond that, I don't get your question. I considered the two code samples, not what? Commented Feb 5, 2018 at 13:42
  • @StoryTeller: See the first code. So, pointers are casted. Isn't that? Why error then? Commented Feb 5, 2018 at 13:44
  • 1
    @mahmood const_casts are used for changing constness; static_cast however is used for changing type. Commented Feb 5, 2018 at 13:48

1 Answer 1

2

const_cast is only to be used for modifying const or volatile qualifiers on pointers to the same type. You cannot use it to cast between unrelated pointer types. A long int * is a pointer to an object type different than int*, so a const_cast will be ill-formed. And that's good, because you shouldn't be caught unaware when doing something risky like that.

The c-style cast will do the conversion at virtually any cost. It's a blunt tool that pays little regard to the type system. The whole reason C++ introduced different types of casts for different scenarios is to avoid this "casting at all costs" behavior. It's to give the programmer control and precision while casting.

Sign up to request clarification or add additional context in comments.

2 Comments

You might want to add "Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior."
@RichardCritten - I don't really, since it's not the subject of the question. I'd rather stay on point, which is the casts themselves. There's possible UB if we use the result of the C-style cast too, due to strict aliasing. Delving into that is a tangent as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.