Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is preferred: (var==null) or (null==var) [duplicate]

Possible Duplicate:
Conditional styles: if (0 == resultIndex) vs if (resultIndex ==0)

I've seen both in code, and I do not know why one is better over the other, but which do you prefer to use, and why?

like image 605
esac Avatar asked Nov 29 '22 20:11

esac


2 Answers

The if(null == var) practice comes from C, where you could accidentally write if(var = null) (note the assignment operator), which would compile (since in C everything not 0 is true) but will be a semantic error. So if(null == var) is a defensive practice, since null is an lvalue (again C/C++ terminology) and lvalues cannot be assigned to.

In modern languages (particularly in C#) compiler will warn you if you do assignment in if statement.

like image 170
Anton Gogolev Avatar answered Dec 05 '22 05:12

Anton Gogolev


I would say var==null because it's more like what you would actually say. "If my variable is null..." makes more sense than any variant of "If null is my variable..." or "If nothing is my variable..." etc.

like image 25
Tyler Avatar answered Dec 05 '22 04:12

Tyler