05 November 2011

What the IF?

If you had these both if conditions, what would you choose to put in your code?

The one:
if(rc == STATUS_SUCCESS)
{
    doSomething();
}

The other:
if(STATUS_SUCCESS == rc)
{
    doSomething();
}


Intuitively, the answer would be (rc == STATUS_SUCCESS), but! What if you forgot one = and wrote (rc = STATUS_SUCCESS) instead? This will be an assignment inside the condition, which will compile, but definitely not what you want to. Now look at the the second option, if you wrote (STATUS_SUCCESS = rc), this will not compile (since STATUS_SUCCESS  is a const) and you'll know you've a bug in compilation.

Note1: you may say: it's not gonna happen to me, I won't forget that =. But believe me, you will forget it and if you didn't go with the second option, you'll be up all night searching for that = (like I did).
Note2: using a Static Analysis Tools (aka Lint-like tools) can expose an assignment within an if-condition warning.

1 comment:

Anonymous said...

I just added your weblog site to my blogroll, I pray you would give some thought to returning the favor.

As a final point , let me thank you for your understanding with my English as (I am convinced you have figured this at this time ,), English is not my primary tongue thus I am using Google Translate to figure out how to write what I really have in mind to articulate.