The common folklore says that:
The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the majority of cases, may indicate a design error and should be avoided.
Even when such a cast is performed, no assumptions shall be made about the size of integers and pointers (casting
void*
toint
is the simplest way to make the code fail on x64), and instead ofint
one should useintptr_t
oruintptr_t
fromstdint.h
.
Knowing that, when is it actually useful to perform such casts?
(Note: having a bit shorter code for the price of portability doesn't count as "actually useful".)
One case I know:
- Some lock-free multiprocessor algorithms exploit the fact that a 2+-byte-alligned pointer has some redundancy. They then use the lowest bits of the pointer as boolean flags, for instance. With a processor having an appropriate instruction set, this may eliminate the need for a locking mechanism (which would be necessary if the pointer and the boolean flag were separate).
(Note: This practice is even possible to do safely in Java via java.util.concurrent.atomic.AtomicMarkableReference)
Anything more?
See Question&Answers more detail:os