Genii Weblog


Civility in critiquing the ideas of others is no vice. Rudeness in defending your own ideas is no virtue.


Wed 23 May 2007, 04:07 PM
I have been programming in C (and C++ when classes were necessary and such) for a long, long time, and I am pretty used to the common gotchas.  Every C programmer runs into the equals sign mistake, where something like that below is used:

if (status = 3)

which sets the value of status to 3 and then evaluates to TRUE since any non-zero value is TRUE, instead of what was meant, which was 

if (status == 3)

which simply evaluates to TRUE or FALSE.  There are many similar issues, but I ran into one I don't ever remember seeing before, even though it was devilishly easy to create.

In a class, there is a boolean value called IsConnected.  In a method within that class, I frequently use the code:

if (this->IsConnected) 

to test that value, since this is the class object itself.  But in a recent interim version of CoexEdit, I accidentally wrote:

if (this-IsConnected) 

Now, if this had been any other pointer other than the current class object, such a mistake would likely show up as a syntax error, since there is no IsConnected local variable, but in this case, there is a local value for IsConnected.  In fact, it was 0, so the object was not connected, so:

if (this->IsConnected) 

would evaluate to FALSE.  But in this case, the wonderful world of pointer arithmetic in C reached out and bit me.  The construction

if (this-IsConnected) 

was perfectly valid, and simply subtracted zero from the pointer represented by this.  Of course, this meant that the statement always evaluated to TRUE, since, as I said before, every non-zero value is TRUE.  Ouch!  Easy to describe, easy to fix, but harder than you would think to figure out since my mind simply saw the construct it expected.

Just in case you think a software developer's life is always easy.

Copyright 2007 Genii Software Ltd.