[postgis-devel] strange behavoir of LW_ABS

Mark Cave-Ayland mark.cave-ayland at siriusit.co.uk
Wed Sep 16 04:55:58 PDT 2009


nicklas.aven at jordogskog.no wrote:

> Hallo
>  
> Maybe this is my lack of c-knowledge, but i'm very confused of the 
> behavior of LW_ABS
>  
> The code below I thought would return -1, but i returns -3.
>  
> Is this expected behavior?
>  
> Why do we have LW_ABS() instead of fabs() ?
>  
> 
> #include <stdio.h>
> #define LW_ABS(a)   ((a) < (0) ? (-a) : (a))
> int main()
> {
> int d,e,f;
> d = 1;
> e = -2;
> f = LW_ABS(d+e);
> printf ("%d\n",f );
> return 0;
> }
>  
> Thanks
> Nicklas

It's because #defines are macros which are simply substituted into the 
code by the pre-processor before the code is compiled. Hence what you 
actually have is this:

f = LW_ABS(d + e)
f = ((d + e) < (0) ? (-d + e) : (d + e))
f = (-1)     < (0) ? (-3)     : (-1)

Probably an extra pair of parentheses may help here...


HTH,

Mark.

-- 
Mark Cave-Ayland - Senior Technical Architect
PostgreSQL - PostGIS
Sirius Corporation plc - control through freedom
http://www.siriusit.co.uk
t: +44 870 608 0063

Sirius Labs: http://www.siriusit.co.uk/labs



More information about the postgis-devel mailing list