Mail Archives: djgpp/1994/11/19/14:04:35
Date: Sat, 19 Nov 1994 04:46:56 -0500
From: davis AT amy DOT tch DOT harvard DOT edu ("John E. Davis")
>A cast does not say "convert this value on the right to this type
>and assign it to the recipient on the left", a cast says "for
>right now, the bit pattern contained in the piece of _storage_ at
>the location indicated by the object being cast IS this type, use
>it as this type and pass the appropriate value under that
>interpretation into the recipient on the left", not at all the
>same thing, it turns out.
I do not think that this statement is correct.
The statement is simply wrong. A cast is a type conversion, pure and
simple. In C, I don't think that you can cast an object to a
structure at all, but I don't have a manual handy. In C++ v1.x
(according to Stroustrup) you can cast a class (struct, union) object
to another type only if there is a conversion operator defined for
that conversion.
The construct that Kent was thinking of, I guess, is a union.
Consider:
float x, y;
long i = 10;
/* assume sizeof (float) == sizeof (long) */
x = (float) i;
y = *(float *) &i;
Here `x' will have the value of 10.0 whereas `y' has the bit
pattern that you re suggesting above. `y' will will almost
certainly not be 10.0 and `x' will not have the bit pattern of `i'.
That is, the float cast above will definitely modify the bit
pattern of i.
This example is bogus because
x = i;
will work without the cast, and it means (in K&R C)
x = (float) (double) i;
because of the "usual arithmetic conversions," at least as I
understand them. (And in K&R C the value of "x = i" is a double!) I
am fairly sure my statements about C++ and C hold for C++ v2 and ANSI
C respectively, but don't have the references at hand.
--Steve
- Raw text -