In traditional C you can do:
int i = 48;
char c = (char)i;
//Now c holds the value of 48.
//(Of course if i > 255 then c will not hold the same value as i).
Which of the c++ casting methods (static_cast, reinterpret_cast) is suited for getting this job done?
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
static_cast
is the one which has to be used here. See this and this SO questions.You should use
static_cast<char>(i)
to cast the integeri
tochar
.reinterpret_cast
should almost never be used, unless you want to cast one type into a fundamentally different type.Also
reinterpret_cast
is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.For more information about C++ casting see:
You can implicitly convert between numerical types, even when that loses precision:
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use
static_cast
for the conversion.Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, onlyconst
orvolatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
,const_cast
andreinterpret_cast
is needed to get the job done.Using static cast would probably result in something like this:
To prevent possible type overflow you could do this:
Where reinterpret_cast would probably just directly convert to char, without any cast safety. -> Never use reinterpret_cast if you can also use static_cast. If you're casting between classes, static_cast will also ensure, that the two types are matching (the object is a derivate of the cast type).
If your object a polymorphic type and you don't know which one it is, you should use dynamic_cast which will perform a type check at runtime and return nullptr if the types do not match.
IF you need const_cast you most likely did something wrong and should think about possible alternatives to fix const correctness in your code.