Possible Duplicate:
How to check for equals? (0 == i) or (i == 0)
Why does one often see "null != variable" instead of "variable != null" in C#?
Why do some experienced programmers write comparisons with the value before the variable?
What is the meaning of NULL != value in C++?
Should I write (x == 1) or (1 == x) to check if a value is equal to 1?
For example,
int k =5;
if( 5 == k )
{
}
is preferred over
if (k == 5)
{
}
Is it considered only for formatting purpose or is there any reason behind it?
Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:
This was intended as a comparison, but it’s now an assignment! What’s worse, it is legal, and it will mess up your program in multiple ways (the value of
kis changed, and the conditional always evaluates totrue).Contrast this with
This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.
That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it’s unlikely to go undetected. Personally I don’t like the second form and since the compiler is there to help I don’t use it.