Sunday, May 20, 2012

C Preprocessor Directives

I had a bug, and I knew it was syntax.  I compile my C code so that all warnings are errors to try to mitigate this class of problem, but it never works.  I decided that I would change how I behave using preprocessor directives.  Firstly, I must say that IBM has great preprocessor documentation in every language that one could speak, but that's not necessary.
Let's start with my problem and my line of code:
if((variable && 0x40000000)!=0){;;}
Variable was not supposed to have a comparison && in it.  It was supposed to be:
if((variable & 0x40000000)!=0){;;}
The problem is that my fingers have habits and I do '&&' more than '&'.  That line of code took about 4 hours to track down. :(  I now have changed my behavior so that it never happens again. The new line is uses C preprocessor directives.
I define my logical AND through a MACRO:
#define _LAND(arg1,arg2) (arg1 & arg2)
I now use it as I would a function in my IF statement:
if(_LAND(variable,0x40000000)!=0){;;}
that results in this code upon compile:
if((variable & 0x40000000)!=0){;;}
so that I never have that mistake again.

No comments:

Post a Comment