static int x[2], *p = x+(x-x); ?

Dave Hanson drh at cs.Princeton.EDU
Fri Sep 14 23:31:29 AEST 1990


In article <1990Sep14.015241.2152 at twinsun.com> eggert at ata.twinsun.com (Paul Eggert) writes:
    ANSI C 3.4 (page 56 lines 22-27) says:
    	More latitude is permitted for constant expressions in initializers.
    	Such a constant expression shall evaluate to one of the following:
    	o	an arithmetic constant expression,
    	o	a null pointer constant,
    	o	an address constant, or
    	o	an address constant for an object type plus or minus an
    		integral constant expression.
    What does ``evaluate to'' mean here?  I thought evaluation yields a value
    (see 3.1.5), but here it seems to yield an expression.

`evaluate to' means to evaluate to a value that can be
computed at compile time, which includes link time.

    For example, which
    of the following declarations are OK, and why?
    
        static int x[2];
        static int *p = 1 + x; /* int+addr, not addr+int */+
        static int *q = x + (int)(0.1 + 0.9); /* Does this ``evaluate to'' x+1? */
        static int *r = &x[(int)(0.1 + 0.9)]; /* Is this equivalent to the above? */
        static int *s = x + (x-x); /* Does this ``evaluate to'' x+0? */

first initialization is legal; 1+x *is* `int+addr'
because x is an address constant.

the 2nd and 3rd are equivalent and are debatable because
floats that appear integral constant expressions must appear
only as the immediate operands of casts (sec. 3.4).
i'd guess that most compilers will accept these, however,
because it's difficult to do otherwise.

even though (x-x) is 0, compilers may not be obliged
to recognize it as 0 because x-x doesn't conform to the allowable
expressions you listed above.



More information about the Comp.std.c mailing list