int num;
...
(int *)num;
Never.
Do.
This!
OriginalGriff already pointed out why this will go wrong (most of the time). I'm going a step further - here are some general concerns:
1. When you need to cast the type of something to something else, this is very often a sign that something is wrong in your code to start with: either you chose an inappropriate type for your local variable, or you are not using your variables correctly. Or maybe something else. Well written code typically doesn't need a type cast. A type cast in C/C++ code is like saying you
"made the kessel run in less than 12 parsecs"[
^] : you're not using the right unit of measurement!
2. Never cast a pointer type to a non-pointer type or vice versa. An address is something entirely different than the object situated at that address. There's just one exception I can think of, only that it's caused by Microsoft and therefore cannot be avoided: the use of DWORD to pass pointers/addresses via Windows events. Microsoft changed their ancient win32 libraries to use the type DWORD_PTR instead. Not much of an improvement, but at least this will use a sufficiently large int type to hold the pointer and work as expected. Still no excuse to use that pattern for your own code.
3. In C++ (your question is tagged as C++) you should not use C-style type casts. Instead you should use
reinterpret_cast
,
dynamic_cast
,
static_cast
, or
const_cast
(see
Type conversions - C++ Tutorials[
^]
4. When you write
some_type variable;
and then
(some_other_type)variable
you are telling the compiler to completely ignore the original declaration of your variable. The compiler will check how much space
some_other_type
requires, and access the memory at the address of your variable using the size of
some_other_type
. If the type sizes don't match, this will likely cause serious problems. Even if they do match, that is no guarantee that the following code will treat your variable correctly. Fortunately, if you use C++ type conversions (see item 3 above), then the compiler will warn you about potential issues of this kind. If you use C-style type casts, the compiler will often remain silent, because to the C compiler, a type cast is the equivalent of saying: "
shut up, I know better than you". And that kind of assertion is almost always false.
5. C style type casts have the annoying(?) side effect of sometimes doing more than just reinterpreting memory: when you cast one numeric type to another, you'll get a meaningful conversion. E. g.
int num = (int)3.14;
will yield 3, not some weird number that you'll get by reinterpreting the IEEE representation of the float value 3.14. That behaviour is certainly something you can learn and get used to, but it's just another stone you can trip over when using type casts without need, or inappropriately.