prev up next   top/contents search

comp.lang.c FAQ list · Question 7.7

Q: Why does some code carefully cast the values returned by malloc to the pointer type being allocated?


A: Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types.

Under ANSI/ISO Standard C, these casts are no longer necessary. It can also be argued that they are now to be discouraged; see question 7.7b. Furthermore, well-defined, low-risk implicit conversions (such as those which C has always performed between integer and floating-point types) can be considered a feature.

On the other hand, some programmers prefer to make every conversion explicit, to record that they have considered each case and decided exactly what should happen (see also question 17.5). Also, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.

(By the way, the language in sections 6.5 and 7.8.5 of K&R2 which suggests that the casts are required is ``overenthusiastic.'')

To some extent, whether you use these casts or not is a matter of style; see section 17.

Additional links: further explanation by Mark Brader

References: H&S Sec. 16.1 pp. 386-7


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North