Clark said:
[snip...]
Pick a language. Either write C or write C++. If you're writing C++,
then use new (and don't cast), if you're writing C, then use malloc (and
don't cast). If, you are writing C, but trying to feed it to a C++
compiler, then why not just write C++, and be through with it?
The alternative you suggest is often simply not possible. For example,
my current project involves a library that needs to link to Matlab and
IDL, which cannot reliably be made to work with C++ compiled code - they
only support C plugins.
As to the point about compiling C code with a C++ compiler. While it is
certainly arguable that the merits of feeding C code to a C++ are
dubious, one has to bear in mind that it is almost a free ride. Most
properly written C code compiles flawlessly in C++, except for a very
small number of cases. Lack of malloc() result casting is by far the
most prominent cause for failure you would normally encounter. Given the
widely shared belief that it is a good thing to throw your code at as
many compilers as you can get your hands on to improve portability, and
maximize the number of warnings you get, I personally think it is worth it.
Then there's the second point I made a couple of times, that I consider
it also proper in terms of elegance: the result of a
"malloc(1000*sizeof(double))" is properly thought of as double*, and
it's only the fact that malloc() must be a general function that forces
it to return a void*. Casting it to its proper type (double *) restores
this obvious anomaly - I think it's proper to do this ASAP.
Now I'm not advocating that we go through all this once again, but I
always get a bit vexed when I see the zealous feeding frenzy that ensues
when anyone dares to mention the malloc casting issue.
Often times, the people telling me to stop compiling my C code with a
C++ compilers ("better download a good lint that will do equally well or
better" - a good point in itself), all of the sudden toss out the stale
"you may fail to notice that you didn't include stdlib.h" when arguing
the malloc cast issue. To them I say:
- make up your mind as to whether you are discussing C89 or C99.
- download a lint, or a free compiler that helps you detect this.
If you use a compiler that doesn't complain on prototype
omission, you have more pressing issues to worry about.
- failure to use strict warning flags in your compiler (just about
the only way you can get hurt by malloc casting nowadays) is a
much more serious software engineering practice mistake than
casting a malloc() result could ever be, even if you don't accept
the advantages.
I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.
Best regards, Sidney