java - Difference between writing a==2 and 2==a -
this question has answer here:
i have question in mind. in many places saw
int a=2; if(2==a){ //some operation }
can tell me advantage on comparing 2==a
in place of a==2
.
some people force error, rather incorrect behaviour, if accidentally typed =
instead of ==
. however:
- it helps in circumstances (when 1 of values compared modifiable , other isn't)
- any decent compiler give warning if make mistake (add parentheses and/or explicit comparison if want assignment)
so real purpose make code confusing read.
a better habit might declare variables const
, unless want them mutable. prevent accidental assignment, while making code easier rather harder reason about.
Comments
Post a Comment