At 19:34 1999.04.01 +0000, holotko wrote:
>Let's say I want to dynamically allocate some memory to an object that
>I am creating using malloc(). Traditionally I do the following:
>
> ObjectType *objectpointer; /* Decl. of pointer to object */
>
> objectpointer = (ObjectType *)malloc(sizeof(ObjectType));
>
>My question. Do I really need to add the type cast (ObjectType *)
>before the call to malloc() ?
>
>Traditionally I have always been taught to include the cast. However,
>some references say that a cast was ONLY required in earlier versions
>of C prior to standard ANSI C. Nonetheless I always type cast as that
>is how I have done it for years and years. Do I really need the cast?
>More precisely, do I really need the cast using gcc?
As far as I know, the theory is :
- KNR C: explicit cast needed
- ANSI C: no explicit cast
- C++: explicit cast needed
In KNR C, malloc() used to return (char *). So the explicit cast was
necessary (to avoid warnings).
In ANSI, malloc() returns (void *) and the rule is that (void *) can be
implicitly cast to (anything *) without a warning. So an explicit cast
is useless.
In C++, the rule is that you cannot cast (void *) to (anything *)
implicitly so you have to cast explicitly (in fact, you're not
supposed to use malloc() at all).
Although, in ANSI C, an explicit cast does no harm, it's useless. I
think it's best to leave it off if only because if you change the
type of the recipient pointer from (foo *) to (bar *), you don't want
to have to change all occurrences of = (foo *) malloc() by
= (bar *) malloc().
That habit of writing (type *) malloc () is just a leftover from
pre-ANSI days. Nowadays, it makes about as much sense as writing
int n = (int) 42;
#include <warning/iamnotanexpert.h>
PS: It would be even better to use
objectpointer = malloc (sizeof *objectpointer);
Andr� Majorel <[EMAIL PROTECTED]>
http://www.teaser.fr/~amajorel/