Why no arithmetic on void *

Barry Margolin barmar at think.com
Wed Jan 23 08:12:12 AEST 1991


In article <561 at taumet.com> steve at taumet.com (Stephen Clamage) writes:
>Void* was an invention of the Committee to cover the case of "pointer to
>something of unknown type".  This allows a guaranteed portable way to
>pass pointers to an arbitrary object to a routine which can make use of
>such a thing, and a way to store pointers to an arbitrary object.

However, it would be nice if void* could also be used as a way to pass
pointers to an array of arbitrary objects.

>When you add/subtract 1 to/from a pointer, the pointer is incremented/
>decremented by the size of the object it points to.  Since the size of the
>object pointed to by a void* is by definition unknown, pointer arithmetic
>is illegal.

This issue came up recently in another newsgroup, I think in the context of
qsort().  The arguments to qsort() include a void* representing the array,
and a size_t containing sizeof(each array element).  Internally, however,
qsort() must cast the void* to a char* in order to increment it.  It seems
to me that ANSI C only goes halfway in providing a generic pointer, because
generic pointer arithmetic must be done by casting to a non-generic type,
namely char*.  I opined that it would make sense for void* arithmetic to
operate in the units that sizeof returns, i.e. define that sizeof void ==
1.  For compatibility sizeof char would also be defined to be 1, but such
use could be deprecated.  Future C standards might then be able to get rid
of the notion that char is the fundamental unit (e.g. systems with bit
addressing could implement void* as bit pointers and sizeof would return
the size in bits, or systems with 16-bit characters but 8-bit bytes could
be supported without needing to resort to wchar_t).

My point is that char* is doing double duty, and it seems like void* was
invented to take over the portion of char*'s role that has nothing to do
with character data.
--
Barry Margolin, Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.std.c mailing list