In some situations, it is highly desirable to have the compiler warn or error on code like reinterpret_cast<void*>(true)
, even though this code is apparently legal C++. For example, it aids in porting to 64-bit platforms.
Casting a 64-bit pointer into an integral type that is smaller than a pointer (such as int
or bool
) is often a bug: you're truncating the pointer's value. Furthermore, the C++ specification doesn't seem to guarantee that you can directly cast a pointer into a smaller integral type (emphasis added):
5.2.10.4. A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined.
Likewise, casting a smaller integral type into a 64-bit pointer (as with reinterpret_cast<void*>(true)
) is often a bug as well: the compiler has to fill in the pointer's upper bits with something; does it zero-fill or sign-extend? Unless you're writing low-level platform-specific code for memory mapped I/O access or DMA, you usually don't want to be doing this at all, unless you're doing something hacky (like stuffing a Boolean into a pointer). But the C++ specification doesn't seem to say much about this case other than that it is implementation-defined (footnote omitted):
5.2.10.5. A value of integral type or enumeration type can be explicitly converted to a pointer.*
A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
@monjardin suggested reinterpret_cast<void*>(static_cast<int>(true))
. If the origin of the error was the mismatch between the integral type's size and the pointer size, then this will work on most 32-bit platforms (where both int
and void*
are 32 bits) but fail on most 64-bit platforms (where int
is 32 bits and void*
is 64 bits). In that case, replacing int
in this expression with a pointer-sized integer type such as uintptr_t
or DWORD_PTR
(on Windows) should work, since conversions between bool
and pointer-sized integers are allowed, and so are conversions between pointer-sized integers and pointers.
Later versions of GCC have the following warning suppression options, but not for C++:
-Wno-int-to-pointer-cast (C and Objective-C only)
Suppress warnings from casts to pointer type of an integer of a different size.
-Wno-pointer-to-int-cast (C and Objective-C only)
Suppress warnings from casts from a pointer to an integer type of a different size.