[LCP]Rounding questions

Greg Black gjb at gbch.net
Sat Sep 7 21:11:05 UTC 2002


Josh Helmer wrote:

| > Finally, when you develop a habit of using unnecessary casts,
| > then you are almost certain to include casts that are actually
| > wrong -- but your cast prevents the compiler from issuing you
| > with a useful diagnostic and then you (and the poor unfortunate
| > people who have to clean up after you) have to take time to find
| > out something that the compiler could have found for free.
| >
| > Just don't use casts -- except in the very few cases where they
| > are required.  There are extra points for providing a single
| > example of such a case.
| 
| OK...   If you have an array of structures and you want to sort the array.  
| The easiest way to go about it is to write a compare function and call 
| qsort().  qsort() will just pass void pointers in to your compare function.  
| You will have to use a cast to do any sort of meaningful comparison.

This is one of those cases I was talking about.  It counts as
rare because qsort() is not used much in real code.  And the
reason behind the actual requirement for the cast in this case
is quite subtle and utterly mysterious to most programmers, who
end up "learning" from this that casts might be needed in all
sorts of inexplicable situations.

One odd thing is that this is one case where you did not need a
cast in traditional C (which needed many more casts than C89),
but where the 1989 standard added the requirement for a cast.

| I have also found that if I want to write (somewhat) generic container classes 

Sorry, this sounds like C++ -- a total waste of time and mental
energy and not the subject of this list or of any comments of
mine.  One of the many weird differences between C++ and C is
the requirement for all sorts of casts in C++.

| Don't get me wrong, I mostly agree with you.  Unnecessary casts should be 
| avoided.   At best they are just noise, and at worst they can hide real bugs, 
| but I am just trying to earn those points you promised... :-)

Well, you would have needed to explain *why* the qsort() casts
are needed (and why that is, at first blush, surprising); and it
would have helped immensely if you had not veered off into C++.

Greg




More information about the linuxCprogramming mailing list