As noted by @MarcGlisse, gcc
provides the -Wc++-compat
warning option. Among other non-C++
-compatible constructs, it warns about silent conversion of void*
.
@AndrewHenle linked to an answer to another question which indicates that requiring an explicit cast has the downside of increasing the likelihood that incompatible conversion may result, for example, if the programmer accidentally casts a numeric value.
I think that's significantly less of a concern, since by an explicit cast the programmer certifies that they know what they're doing. Neverthless, even that small drawback can be addressed by using the following macro in conjunction with -Wc++-compat
:
#define VOID_CAST(T, x) ({ __typeof__(x) void_cast_x __attribute__((__unused__)) = ((__typeof__(x))((void*)(x))); ((T*)(x)); })
With luck, the "useless" assignment will be optimized out and the benefit of using VOID_CAST
is that it will generate an error or warning if x
is not a void*
to begin with.