First of all, most people prefer the second form, since it feels "more natural"; the first form is felt as "reversed", and in fact is often called "Yoda conditional".
The rationale behind using the first form is to avoid accidental assignment when typing =
instead of ==
by error. Since in a conditional you can write any expression, =
is allowed, so in case of mistyping the instruction
if(k = 5)
{
}
won't check if k
is equal to 5
, but will assign 5
to k
and, since =
returns a reference to its left hand operator, the condition will be evaluated as true and the if
body will always be executed.
On the other hand, if you typed =
instead of ==
in the Yoda conditional you would get
if(5 = k)
{
}
which results in a compilation error, since you can't assign anything to a literal (5).
Although they look like a good idea, "Yoda conditionals" are quite weird looking, and, most importantly, almost any good compiler with warnings turned on will warn you anyway if you write an assignment inside a conditional expression, so most people just use the "natural looking" form.