K
Keith Thompson
Morris Keesan said:k&r errata #142:
On the other hand, pre-ANSI, the cast was
necessary [from malloc return to other pointer types]
I've seen this claim many times, but I've never used any compiler for
which the cast was necessary, nor seen any definition of the language
in which it was necessary, including, among others, the language
definition as published in K&R 1, or the (almost identical) C Language
documentation in the version 6 or 7 Unix documentation.
K&R1 Appendix A 14.4, "Explicit pointer conversions" (page 210):
Certain conversions involving pointers are permitted but have
implementation-defined aspects. They are all specified by means
of an explicit type-conversion operator ([sections] 7.2 and 8.7).
Some compilers may have been lax enough to permit, for example,
converting from char* (the result type of malloc) to int* without a
cast, but K&R1 strongly implies that a cast was required. (There was
no void* type.)
An example on the next page is:
extern char *alloc();
double *dp;
dp = (double *) alloc(sizeof(double));
*dp = 22.0 / 7.0;
Going back to 7.14, (page 191), the description of assignment is
somewhat ambiguous:
In the simple assignment with =, the value of the expression
replaces that of the object referred to by the lvalue. If both
operands have arithmetic type, the right operand is converted to
the type of the left preparatory to the assignment.
Note that it doesn't mention implicit pointer conversion. But later
in the same section:
The compilers currently allow a pointer to be assigned to an
integer, an integer to a pointer, and a pointer to a pointer of
another type. The assigment is a pure copy operation, with no
conversion. This usage is nonportable, and may produce pointers
which cause addressing exceptions when used. However, it is
guaranteed that assignment of the constant 0 to a pointer will
produce a null pointer distinguishable from a pointer to any
object.
My reading of this is that implicit pointer conversion is not
permitted by the language, but compilers allow it anyway.
(Of course a lot of this changed with the 1989/1990 and 1999
C standards.)