"Ralf" <> writes:
> Regarding numerical types, in my view, casts fall in one of two
> categories:
> 1. Casts that change the value of an object
> 2. Casts that are actually redundant, but get rid of compiler/lint
> warnings
>
> As an example, consider this code:
>
> unsigned int ui;
> ...
> unsigned char uc = (unsigned char)ui;
This is precisely equivalent to
unsigned int ui;
...
unsigned char uc = ui;
You could argue that the version with the cast is more explicit. On
the other hand, it has to repeat the target type, and it introduces
possibilities for error. For example, suppose you change the type of
the variable to unsigned short, but forget to change the cast.
*All* casts should be viewed with suspicion. There are a few cases
where they're necessary:
Passing an argument to a function that takes a variable number and
type of parameters. (You should always have a visible prototype
for any function you call; for ordinary functions, this will
impose an implicit conversion.)
Arithmetic conversions within expressions. For example:
int x = ...;
int y = ...;
long product = (long)x * (long)y;
Without the casts, the multiplication will be done in type int,
and the value converted to long afterwards. (Actually only one of
the casts is necessary, but I like the symmetry.) (And yes, I'm
assuming that long is wider than int.)
Pointer conversions in deliberately non-portable code.
Probably other cases I haven't thought of.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.