Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some experienced programmers write comparisons with the value before the variable? [duplicate]

Possible Duplicates:
How to check for equals? (0 == i) or (i == 0)
Why does one often see “null != variable” instead of “variable != null” in C#?

I've been having a look at an odd tutorial here and there as well as some DirectX code and noticed that many experienced C++ programmers write expressions in the following way:

(<constant> == <variable>)

rather than what my conventional wisdom seems to prefer:

(<variable> == <constant>)

E.g. if (NULL == ptr) rather than if (ptr == NULL). I prefer the second alternative, if there are no other reasons for choosing the former, my reason being that the variable seems to be the "receiving" end of the expression.

But I suspect the former is used to avoid inadvertently assigning the value of the constant to the variable by using = rather than ==. Would that be correct?

like image 378
Kristian D'Amato Avatar asked Jul 22 '10 13:07

Kristian D'Amato


4 Answers

That used to be the case, yes. Of course, nowadays almost all compilers warn about assignments in if() conditions, so the advantage is only there for people who routinely suppress warnings.

like image 144
Kilian Foth Avatar answered Nov 11 '22 10:11

Kilian Foth


Yes, that's correct. It's to detect the typo of = instead of ==.

like image 26
mdma Avatar answered Nov 11 '22 11:11

mdma


This has been dubbed as a "Yoda Conditional"!

See here https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined

I really like that term because:

if(Light::On == light)

Reads as:

"If on is the light"

As stated already, this is used to prevent incorrect assignment. It could be argued that this practice is archaic based on modern IDEs but I still think it is good practice.

like image 9
Robben_Ford_Fan_boy Avatar answered Nov 11 '22 10:11

Robben_Ford_Fan_boy


its because you cannot assign a value to a constant, so if by mistake you put = instead of == the compiler throws an error, alerting you

like image 6
Necrolis Avatar answered Nov 11 '22 11:11

Necrolis