if (true condition) runs here

The simplest stuff to learn about c and c++ programming is ” if “. Not only c/c++, almost all programming language have ” if “.

if (/* condition true*/1 )
      //codes runs here

The second basic:
0 (ZERO) is FALSE, 1 (ONE) is TRUE. How about -1 (-ve ONE)? It is TRUE as well.

I tends to forget this, because I always write function that return -1 when failed and return 1 when success. Somehow, -1 is FAIL = is FALSE That is makes sense but it is WRONG. What is the problem I might face? Let say I have written a function Enable() returns 1 if something enable and returns 0 when it is not.

int Enable()
      //let say have external variable contain the availability
     return Machine.Avai;

//further down I check with if
if (Enable())
      //do some process
     //do other process

It seems okay, but maybe after many months, and the project needs to be enhance. You need to initialized the Machine.Avai with -1, and at middle of somewhere, then you check whether it is already set? if not set then set it.

int InitAvai()
      return 1;

int CheckAvai()
     if (Machine.Avai==-1)//not yet set
     return 1;

You have done your modification and compiles happily, but it introduce a bug point. After calling InitAvai(), if you call if(Enable()), by right if Machine.Avai is -1 means not Enable, but now the case is that:

if(Enable()) //Enable will returns -1, so if(-1) is true condition
       //process this line, which is wrong in purpose.

My point is, try not to use if(Enable()), or use it with care.
Alternatively, you can do this:

if (Enable()==1) //seems you know enable should be 1, and ==1 is more visible to user
if (Enable()>0) 

One thought on “if (true condition) runs here

  1. hehe, thanks for sharing this surface. It takes time and training to spot this kind of mistake/misconception, but better spot it early than never :>

Leave a Reply

Your email address will not be published. Required fields are marked *