void*

Bjarne Stroustrup bs at alice.UucP
Tue Aug 12 13:33:37 AEST 1986


> What are the (proposed and current) legal operations for "void *" besides
> assignment, casting, and passing as a parameter?
> 
> -- Tom Stockfisch, UCSD Chemistry

In C++, you can also use the comparison operators ==, !=, <, <=, >, >=, and the
negation operator !.
Pointer arithmetic is specifically disallowed (since you by definition do not
know the size of the object pointed to).
Conversion from any pointer type to void* is defined, but there is no conversion
the other way:

	char* pc = &some_char;	// OK if some_char is a char
	void* pv = &something;	// OK
	pv = pc;		// OK; standard conversion
	pc = pv;		// not OK: no standard conversion
	pc = (char*) pv;	// OK
	if (pc == pv) ...	
	if (pv == 0) ...
	if (!pv) ...
	if (pv < pc) ...

In addition, the draft ANSI C proposal allows uncasted assignment of a void*
to a non-void pointer. This, I consider to be an unnecessary weakening of C's
type system; in the long run it will become a rather serious nuiscance.
C++ does not allow this and I hope that ANSI C will not allow it either.

The reason for the proposal's rule is simple. Malloc() returns a void* and
if a void* can be assigned to any pointer without a cast you can write

	double* pc = malloc(100*sizeof(double));
	char* pc = malloc(100);

rather than

	double* pc = (double*) malloc(100*sizeof(double));
	char* pc = (char*) malloc(100);

I don't consider this minor notational convenience a sufficient reason to
create a new hole in the type system. A better solution, which unfortunately
does not appear to be open to the ANSI C committee, is to have a free store
allocation operator, such as C++'s new:

	double* pc = new double[100];
	char* pc = new char[100];

An implicit coersion to void* is OK, but an implicit coersion
from void* to another pointer type is not. The reason is the former,
simply throws information and away whereas the latter implicitly ``adds''
information. Allowing the latter (as the ANSI C proposal does and C++ does not)
would provide a new way of converting types without using casts:

	void* p;
	double* pd;
	char* pc;

	pc = pd;	// illegal
	p = pd; pc = p;	// legal under the current ANSI C proposal



More information about the Comp.lang.c mailing list