type cast in initializer
Mark Brader
msb at lsuc.UUCP
Sat Feb 8 15:22:46 AEST 1986
In regard to...
> > > int x = 0;
> > > char *ptr = (char *) &x;
> > In any case, I'm not sure why you'd want to do what your example does,
> >since the cast here is a no-op.
Joseph S. D. Yao responds...
> Two reasons are immediately obvious...
and goes on to give three reasons. Two are excellent, but the other is wrong:
> ... on some computer
> architectures, e.g. one with type-tagged pointers, the cast may
> [ NOTE: n o t "will", just "may" ] not be a no-op.
If this is not a slip, it stems from a misconception of casting which
is a Frequently Repeated Error in this newsgroup. (If I remember what
somebody posted a while ago, the error found its way into a DECUS C
manual, which accounts for its widespreadness.)
The cast specifies a conversion. If TTT and UUU are types, and
we have:
TTT t; UUU u; /* ..... */ t = u;
then at that point the expressions t and (TTT)u are interchangeable.
In the case of type-tagged pointers, the cast specifies that the
pointer tagged "int" is to be converted to one tagged "char" and
stored in the variable, but so would the initialization or assignment
without the cast, if the compiler accepts it at all.
Mark Brader
[ The current ANSI draft C standard states:
Preceding an expression by a parenthesized type name
c o n v e r t s t h e v a l u e [ emphasis mine]
of the expression to the named type. This construction is called a cast.]
More information about the Comp.lang.c
mailing list