Felix Kater wrote:
I haven't been thinking about it for years but recently I've stumbled on
the fact that 'casting' is actually doing (at least) two different
things:
On the one hand 'casting' means: 'Change something into somthing
else'. Example: double d=9.99; long l=(double)d;
That's fine, although it's a silly cast. `d' is already
a `double', so "converting " it to a `double' is unnecessary.
(The `double' result, whether "converted" or not, will then
be converted to `long' for initializing `l'.)
On the other hand 'casting' means: 'Treating something as something
else without change'. For instance when casting function pointers.
Would You agree?
No. A cast is an operator that performs a conversion (even
if the conversion is vacuous, as above). There is no such thing
as a "let's pretend" cast.
However, casts can convert a pointer of one type into a pointer
to another type, and there is something like a "let's pretend"
effect if the converted result is then used to access a pointed-
to object or function:
int i = 42;
unsigned char *p = (unsigned char*) &i;
printf ("The individual bytes of %d are:", i);
while (p < (unsigned char*)(&i + 1))
printf (" %d", *p++);
printf ("\n");
Line two takes the pointer-to-int value `&i' and converts
it to a pointer-to-unsigned-char, which it then stores in `p'.
There is no "let's pretend" at all: A value is converted from one
type to another, and that's that.
There's another such conversion on line four, where another
pointer-to-int is converted to pointer-to-unsigned-char for
purposes of comparison. Again, there's no "let's pretend:" the
cast converts the value `(&i + 1)' to a different type.
The "let's pretend" occurs on line five, where a pointer
to one type (unsigned char) is used to manipulate an object of
a different type (int). Observe that there is no cast in line
five: We are "treating something as something else without
change" by accessing it with different kinds of pointers, not
by applying a cast to it. (No cast is ever applied to `i'.)
IMO this difference between 'conversion' and 'treatment' isn't probably
pointed out enough to C newcomers and may be one reason for the danger
of casts.
It would be a disservice to newcomers to point out a difference
that doesn't exist. For the same reason, most introductory texts
omit mentioning the temperatures of C's data types.
--
Eric Sosman
es*****@acm-dot-org.invalid