What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
The use of NULL == condition
provides more useful behaviour in the case of a typo, when an assignment operator =
is accidentally used rather then the comparison operator ==
:
if (bCondition = NULL) // typo here
{
// code never executes
}
if (NULL = bCondition) // error -> compiler complains
{
// ...
}
C-compiler gives a warning in the former case, there are no such warnings in many languages.
It's called Yoda Conditions. (The original link, you need high rep to see it).
It's meant to guard against accidental assignment =
in conditions where an equality comparison ==
was intended. If you stick to Yoda by habit and make a typo by writing =
instead of ==
, the code will fail to compile because you cannot assign to an rvalue.
Does it worth the awkwardness? Some disagree, saying that compilers do issue a warning when they see =
in conditional expressions. I say that it simply happened just two or three times in my lifetime to do this mistake, which does not justify changing all the MLOCs I wrote in my life to this convention.
There is no difference. It is an ancient way of defensive programming that has been obsolete for over 20 years. The purpose was to protect from accidentally typing = instead of == when comparing two values. Pascal programmers migrating to C were especially prone to write this bug.
From Borland Turbo C released in 1990 and forward, every known compiler warns against "possibly incorrect assignment", when you manage to type out this bug.
So writing (NULL == bCondition) is not better or worse practice than the opposite, unless your compiler is extremely ancient. You don't need to bother about writing them in any particular order.
What you should bother with, is to adapt a coding style where you never write assignments inside if/loop conditions. There is never a reason to do so. It is a completely superfluous, risky and ugly feature of the C language. All industry de-facto coding standards ban assignment inside conditions.
References:
- MISRA C:2004 13.1
- CERT C EXP18-C
Many people prefer writing NULL == bCondition so that they accidently don't assign the NULL value to bCondition.
Because of typo it happens that instead of writing
bCondition == NULL
they end up writing
bCondition = NULL // the value will be assigned here.
In case of
NULL = bCondition // there will be an error
It's simply a good defensive measure. Some may also find it more convenient to read. In case of a mistyped assignment instead of the equality operator, the compiler will attempt to modify NULL
, which is not an lvalue and will produce an error message. When using bCondition = NULL
, the compiler might produce a warning about using an assignment as a truth value, a message which can get lost and go unnoticed.