type cast in initializer

throopw at dg_rtp.UUCP throopw at dg_rtp.UUCP
Mon Feb 10 06:43:31 AEST 1986


[ The case under discussion:
        int     x = 0;
        char    *ptr = (char *) &x;
]

[keesan at bbncc5.UUCP]
> >    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.

[hadron!jsdy at seismo.{CSS.GOV,ARPA,UUCP}]
> Two reasons are immediately obvious.  The less compelling is that
> lint tells you to.  The more compelling is that 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.  Some compilers
> will even reject the un-cast initialisation out of hand.

Acutally, for K&R C, Keesan is correct.  I was about to post just about
what Yao posted, but I looked it up in K&R, and found two interesting
points, the first about casts, and the second about initializations.

    [from The Book, page 42, paragraph 3, line 5, read in the style of
          a Gregorian chant for best effect]
    The precise meaning of a cast is in fact as if *expression* were
    assigned to a variable of the specified type, which is then used in
    place of the whole construction.

    [from The Book, page 198, paragraph 5]
    When an initializer applies to a *scalar* (a pointer or an object of
    arithmetic type), it consists of a single expression, perhaps in
    braces.  The initial value of the object is taken from the
    expression; the same conversions as for assignment are performed.

I'm not sure what ANSI says about it, but it's probably something
similar.

So, casts are equivalent to assignment, and initialization (for scalars)
is equivalent to assignment, therefore initialization is equivalent to a
cast, and the explicit cast is redundant.  But I'd still put it in,
myself, since

> Come to think of it, the 'lint' reason is not less compelling.

is right on the money... if you are doing something perverse like this
with types, you had better justify yourself to lint (or some other
typechecker).  If you don't lint your code and pay attention to what
lint says, you are just coding in a peculiar assembly language.
-- 
Wayne Throop at Data General, RTP, NC
<the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list