Hacker News new | ask | show | jobs
by gjulianm 4843 days ago
In my university they always told me to cast the return of void * functions, I thought it was just to avoid the warning saying "automatic cast of void* to int*" or similar.

Thanks, I will take that into account.

1 comments

It is true in C++, not in C where void* needs no casting.

People tended to confuse C++ with C more in the past, as they had not diverged as much as they have now.

An annoying thing C++. Anyone know the history/rationale of this change?
It is supposed to provide you more checking by disabling automatic cast from void* to any other pointer. This makes sense in C++ since casting a pointer to a class can trigger some address adjustement if the target class of this instance pointed to is multiple derived (and maybe in other cases?). There is no way such adjustment can happen if the source type is void*, because then you don't know what the source type really is.
As far as I know, this is exactly the rationale, actually. Say you have:

  struct a { int a;}
  struct b { int b;}
  struct c : a, b { };

  c myc;
  c* p1 = &myc;
  b* pb1 = p1; // correctly points to myc's base b, which is offset

  void* p2 = &myc;
  b* pb2 = p2; // Would not point at instance of b, compile error
If I need void*-casting code to compile on both C and C++ compilers, I use a macro like this:

  #ifdef __cplusplus
  #define STATIC_CAST(T, EXPR) static_cast<T>(EXPR)
  #else
  #define STATIC_CAST(T, EXPR) (EXPR)
  #endif
This leaves the conversion to be implicit in C, and uses the stricter static_cast in C++ to catch certain types of likely-unsafe conversions, such as the aforementioned cast from int to pointer.