Search code examples
c++ccoding-style

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


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?


Solution

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