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?
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.
Yes, that's correct. It's to detect the typo of =
instead of ==
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With