Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!csd4.csd.uwm.edu!markh From: markh@csd4.csd.uwm.edu (Mark William Hopkins) Newsgroups: comp.lang.c Subject: Re: Casting malloc() in ANSI C? Message-ID: <1651@uwm.edu> Date: 26 Dec 89 17:40:29 GMT References: <24969@cup.portal.com> Sender: news@uwm.edu Reply-To: markh@csd4.csd.uwm.edu (Mark William Hopkins) Distribution: usa Organization: University of Wisconsin-Milwaukee Lines: 37 In article <24969@cup.portal.com> Kevin_P_McCarty@cup.portal.com writes: >This is a question on recommended style. > >In ANSI C, assigning a void pointer to any pointer variable is >legal, so casting the value returned by malloc() to the >appropriate pointer type is no longer necessary. As a matter of >recommended style, should the redundant cast be retained? One way around the issue is to define the macro: #define make(Type) (Type *)malloc(sizeof(Type)) or, perhaps: #define make(Type, N) (Type *)malloc((N)*sizeof(Type)) and use it to replace malloc as much as possible. If you're going to use information about the Type anyway (in sizeof()), you might as well cast malloc and then hide everything. So you can have it both ways: extra (potentially useful) information, without the clutter, and not only that, but with LESS clutter than if you had just decided to eliminate the type casting out of a concern for making the code less cluttered. And if that isn't enough, you can modify it easily without ever even touching on the issue of whether malloc should be casted or not: #ifdef ANSI #define make(Type) malloc(sizeof(Type)) #else #define make(Type) (Type *)malloc(sizeof(Type)) #endif ... presumably this would be in a header file, all invisible to the normal programmer.