1

Ok most answers on SO say that reinterpret_cast is most dangerous cast, can do whatever..what not.., it can reinterpret bits of one type like another type. So my question is why does static_cast<char>(int(0)) works but reinterpret_cast<char>(int(0)) not? is it due to size difference of argument type and destination value type?

reinterpret_cast<char*>(&Some_double_var) works.

How does implementation knows which cast works in what cases?

Thanks

Angelus Mortis
  • 1,534
  • 11
  • 25
  • The second example probably works because all pointer types have the same size. But an attempt to interpret `sizeof(int)` bytes as a `char` is not sensible. – oarfish Jan 10 '16 at 17:19
  • @oarfish so it's size issue with `reinterpret_cast` i.e size of destination and source types must have same size? – Angelus Mortis Jan 10 '16 at 17:19
  • I think that is a reasonable explanation, but honestly I have no idea. – oarfish Jan 10 '16 at 17:20
  • The implementation knows what each cast does and whether it works because it is built to comply with a standard that has the definitions of what is valid, what not and what the expected behavior of each operation is. – David Rodríguez - dribeas Jan 10 '16 at 17:34
  • @DavidRodríguez-dribeas Sir I get you sarcasm which probably meant -> have a look at C++ standard doc lazy guy :D . Thanks anyways for direction :) – Angelus Mortis Jan 10 '16 at 18:56
  • @AngelusMortis: It was not a sarcastic comment. Compilers apply the definition of a language, how a compiler knows what is allowed or not is defined in the specification of the language. I did not intend to imply *look at the standard lazy guy*, just that the question *how does a compiler know how the language is* is a rather awkward question. – David Rodríguez - dribeas Jan 10 '16 at 23:14

1 Answers1

1

A reinterpret_cast is the most dangerous cast, but it can't do anything. It can just do the most dangerous things. There is a specific list of things a reinterpret_cast can do. Converting from one scalar value to another is not in that list, since a static_cast is intended to be used for that instead. The list for reinterpret_cast is basically:

  • Doesn't cast away constness
  • Converts pointer to integral.
  • Converts integral to pointer.
  • Converts between function pointer types.
  • Converts between object pointer types.
  • Converts between reference types.
  • Converts between pointer-to-member types.

Each type of cast is intended to do a specific thing. For example, a reinterpret_cast won't do the same things that a const_cast will do.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132