Chris Croughton said:
On Wed, 26 Jan 2005 19:37:51 GMT, Keith Thompson
Yes, it makes it clearer in the view of a lot of programmers (and yes
there are also a lot of programmers who think it makes it more obscure,
and both groups will say that the other is 'wrong').
The difference is that the programmers who think casting malloc() is a
good idea (except for the rare C/C++ compatibility requirement) really
are wrong. (Note the lack of a smiley here.)
Seriously? I meant that as a joke.
Ok, how about this: a coding standard that requires all identifiers to
be of the form id_NNNN, where NNNN is a decimal number, and a
separately maintained table describes what each one is used for.
If an imposed coding standard is sufficiently stupid, you as a
programmer need to say so, and if management insists on enforcing it,
they need to be told what it's going to cost in productivity.
[...]
It's not bad code, it's self-documenting code. If I see:
fred = (char)bill;
then I know that the value of bill is being coerced to fit in a char,
without having to wonder whether fred is a char or an int.
It tells you the value of bill is being coerced to fit in a char, but
it doesn't tell you the type of either bill or fred. If you change
fred from char to short, do you go through the code and change all the
casts? Keep in mind that the compiler won't complain about
fred = (char)bill;
even if fred is a short. For example, it might silently truncate the
32-bit value of bill to 8 bits before assigning it to the 16-bit
object fred.
Having found a number of bugs caused by someone declaring a variable
of the wrong type (I recently couldn't understand why a buffer
wasn't being input, until I found that my "convenient size" of 256
was being put into an unsigned char and being silently truncated to
zero!) I would rather see explicit casts where truncation occurs.
I would rather not see explicit casts unless they're actually
necessary. You can use a cast to document the type of an expression,
but that's really an abuse of the constuct. In the above assignment
what *you* mean by the cast is "assign this value to fred -- and by
the way treat it as a value of type char". What you're really telling
the compiler is, "Take the value of bill, coerce it to type char (I
don't char what type bill happens to be), and assign the result to
fred (I don't care what type fred happens to be) -- and don't
complain, because I promise you I know what I'm doing *wink wink*."
C performs implicit conversions in many contexts (too many for my
taste, but that's a separate issue). An explicit conversion via a
cast doesn't inhibit the implicit conversion; it's still performed
after the cast is performed. I'd often rather make my conversions
explicit rather than implicit, but C doesn't really give me that
choice.
[snip]