Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

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.