A define problem

John Stanley stanley at phoenix.com
Thu Jan 10 05:36:20 AEST 1991


jak at sactoh0.SAC.CA.US (Jay A. Konigsberg) writes:

> In article <1991Jan8.012923.3390 at oswego.Oswego.EDU> hunter at oswego.Oswego.EDU 
> >In article <440 at bally.Bally.COM> siva at bally.Bally.COM (Siva Chelliah) writes
> >
> >>#define half(x) (x)/2
> >>main ()
> >>{
> >>  int i=5;
> >>  printf( "i/2 = %d\n",half(i-5));
> >>}
> >>This program prints 3 instead of 0 !  How can I make it print 0 ?
> >
> >You could get a new compiler. ;^}
> >
> 
> Bzzzt. Wrong, but thank you for playing :-)
> 
> Look at what is being passed to "half()".

    Bzzzzt. Wrong, but thank YOU for playing. There is nothing "passed"
to half(). Half is a preprocessor macro that is expanded by the
preprocessor, and not a function to which things are passed. 

> i=5
> half(i-5) or half(5-5) or half(0)

   Do you REALLY think the preprocessor is smart enough to perform the 
subtraction and expand the macro "half" with a parameter of 0? To the
preprocessor, (i-5) is not the same as (5-5) is not the same as (0).

> which becomes: (0)/2 - which is 0.

   Try "i-5/2".

   It looks like the preprocessor is discarding the () around the x in
the macro expansion. Instead of generating the expression "(i-5)/2" it
is generating "i-5/2". "5/2" is 2 (integer arithmetic), and 5-2 is 3. One
would think the preprocessor should honor the existing (), but it must 
not be doing it. Try running just the preprocessor and looking at the
generated code. You might not need a whole new compiler, just the
preprocessor.

   As was previously suggested, try defining half(x) as ((x))/2. Or, if
all you want is a way to print 0 (which is all you said you wanted -- "How
do I make it print 0?") then replace the expression "half(i-5)" in the
printf with "0". :-)


   Since one reason to use #defines is to shorten the amount of typing,
why not just do the division yourself? You save two characters in each
use.



More information about the Comp.lang.c mailing list