[LCP]Rounding questions

Greg Black gjb at gbch.net
Mon Sep 9 10:31:12 UTC 2002


Steve Baker wrote:

| Josh Helmer <jhelmer4 at cox.net> wrote:
| > > As you know, malloc() returns a `void *'.  It is automatically
| > > converted to a `struct foobar *' by the above assignment and
| > > there is no need, in this case, for a cast (and there are good
| > > reasons for saying that a cast here is `wrong').
| >
| > Sorry... I feel like a dumbass for having spent so much time defending my own 
| > ignorance.  I knew that you didn't have to cast the return from malloc (and I 
| > don't), but never made the connection that you could just assign a void 
| > pointer to any type of pointer in other cases too...  I went back and wrote 
| > some quick test code and lo-and-behold the casts that I had always believed 
| > were necessary were not...  Oops..
| 
|   You may not have to cast, but there is nothing inherently wrong with doing
| so, in fact, doing so almost counts as documentation, or at least, as much
| documentation as some programmers provide.  It can be a problem when that
| "documentation" is wrong, but I wouldn't go so far as to advocate it's
| complete removal.  You probably use casts as you do, because you were taught
| to, and it's not wrong to emulate your teachers, especially when they are the
| likes of Kernighan and Ritchie.

Would you care to give at least one example of where K&R
disagree with me?

|   There is more than one way to do things in C, there is more than one style
| of programming.  Don't be too concerned with what others think of yours so
| long as you're productive and produce good working code.  We could all sit
| around and nit-pick and criticize each others coding style all day long, but
| nothing would come of it.

This is not nit-picking.  Incorrect or needless use of casts can
frequently mask real errors that a compiler would otherwise have
been able to diagnose.  It's bad practice, no matter what you
think.

Greg




More information about the linuxCprogramming mailing list