Article # 657, added by Geoworks, historical record
| first |
previous |
index |
next |
last |
Do not use TRUE for comparison in GOC
In geos.h, TRUE is defined as: >>>>> #define FALSE 0 #define TRUE (~0) /* Use as a return value, *not* for comparisons */ <<<<< This is different from the #define in .h files provided in most C compilers out there. This means that in GOC you can do things like: Boolean hasData; if ( hasData ) { ...... } but you cannot do things like: if ( hasData == TRUE ) { ...... } The reason is that C expressions that evaluate a condition generate the value 1 if the condition is met. (This is described in the K&R book and most compilers do it this way.) Therefore, if you have something like this: Boolean greaterThan( int a, int b ) { return a > b; /* returns +1 or 0 */ } ...... Boolean fiveGtFour; fiveGtFour = greaterThan( 5, 4 ); if ( greaterThan( 3, 2 ) == TRUE && fiveGtFour == TRUE ) { ...... } your code will not execute correctly. Rather, you should do if ( greaterThan( 3, 2 ) && fiveGtFour ) { ...... } There are quite a bit of existing code that uses TRUE for comparison, yet still works. It happens to work because in some cases the variable being compared was explicitly assigned to the constant "TRUE". However, please do not use TRUE for comparison in the future. Here is an explanation on why TRUE in GOC is defined as ~0 but not 1: --------------------------------------------------------------------- I would guess it's because TRUE needs to match the geos.def definition, in case people want to compare a return value (for whatever reason) to it, rather than just using the logical test in C. I think it's ~0 in assembly partly because the "AND" operator is bitwise, not logical, so if one were to say: if RANDOM_CONSTANT and TRUE If RANDOM_CONSTANT were other than 1, you'd still want the thing to evaluate true. I know some compilers use -1 for true, rather than 1. not sure what the reasoning is.