Is #define THING -10 completely safe?

Andreas Krey krey at i30fs1.ira.uka.de
Tue Jan 29 03:05:02 AEST 1991


In article <745 at caslon.cs.arizona.edu>, dave at cs.arizona.edu (Dave P.
Schaumann) writes:
> In article <14999 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
> |In article <1991Jan27.233142.28302 at watdragon.waterloo.edu>
ccplumb at rose.uwaterloo.ca (Colin Plumb) writes:
> |-As all loyal followers of the Obfuscated C code contest know,
> |-array[i] == *(array+i) == *(i+array) == i[array].  So
> |-#define X1 -10
> |-#define X2 (-10)
> |-[...]
> |-printf("%d, %d\n", X1[p], X2[p]);
> |-Will print "-35, 15".
> |
> |No, that's a ludicrous misinterpretation of the situation.  The
> |compiler does NOT perform a textual "rewrite" of the [] expression
> |then reparse it.
> 
> 
> This works as Colin says on my machine (compiling with gcc).  Here is the
> full program:
>
[ program deleted ] 
> 
> If Colin's interpretation is wrong, what *is* happening?
> 
> Dave Schaumann		|  And then -- what then?  Then, future...
> dave at cs.arizona.edu	|  		-Weather Report

'X1[p]' -> preprocessor -> '-10[p]'
That is, by precedence rules, the same as '-(10[p])', same as '-(p[10])',
which is 35 in the program above.

The latter conversions are no textual 'rewrites'; the compiler simply reduces
the a[b] first, then the -a. Thus array reference goes before negation
and there
is the negative sign. X2 on the other hand is parsed differently because of the
braces around -10. (The [] is actually a commutative operator, although the 
concrete syntax may suggest otherwise.)

Besides I nearly always brace all replacement texts with more than one token 
and all macro parameters within them, just to be sure.

.signature: No such file or directory



More information about the Comp.lang.c mailing list