Mail Archives: djgpp/1999/07/20/07:25:42
Edward Hill wrote in message <379450DC DOT E0B363B5 AT nochance DOT com>...
>Michael Stewart wrote:
>: The code I posted used a cast to tell the compiler that the allocated
>: will be used as float*. Ed didn't use a cast.
>It's good practice not to cast, malloc doesn't require a cast and a cast
>can sometimes mask errors.
>: malloc returns void* and by using a cast it'll prevent the compiler
>: complaining about converting between types. It should be quite safe to
>: the memory without the cast though.
>If the comiler is complaining about not casting malloc's return, this
>is one of the cases where casting it will mask an error.
>If my compiler moans about not casting the return of malloc it's
>because I have forgotten to #include <stdlib.h>
>You should only ever need to cast malloc when dynamically allocating
>a mutidimensional array.
I've just been reading the C FAQ
(ftp://rtfm.mit.edu/pub/usenet/news.answers/C-faq/faq) and it says this
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,
and in fact modern practice discourages them, since they can
camouflage important warnings which would otherwise be generated
if malloc() happened not to be declared correctly; see question
7.6 above. (However, 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.)
So as Ed said, don't use casts in C (unless you want them to be compatible
- Raw text -