First code:
if(i==0) {// do instructions here}
Second code:
if(0==i) { // do instructions here }
What
Functionally, there is no difference.
Some developers prefer writing the second format to avoid assignment typos(in case you miss a =
), so that compiler warns of the typo.
The second is famously known as Yoda Condition.
I say there is no difference because, you cannot guard yourself against every minuscule detail and rely on compiler to cry out aloud for you.If you intend to write a ==
you should expect yourself to write a ==
and not a =
.
Using the second format just leads to some obscure non-readable code.
Also, most of the mainstream compilers warn of the assignment instead of equality typo by emitting an warning once you enable all the warnings(which you should anyways).
no difference, some people prefer the second one to catch the common mistake of doing
assignment (=
) instead of equality test (==
)
0 = i
would fail at compilation
Yep they are same as far as C# is concerned. For more complex situations visit A==B vs B==A, What are the differences
For C++, it's possible, though unlikely, that there could be a difference. It depends upon what i's type is. e.g.
struct Foo
{
int x;
};
bool operator==(Foo lhs, int rhs)
{
return lhs.x == rhs;
}
bool operator==(int lhs, Foo rhs)
{
std::cout << "Hi!";
return true;
}
Someone who writes code like that should of course be shot.
Functionally, they are the same in C; I'm not sure about other languages where ugly things like operator overloading come into play.
Stylistically, the latter is extremely counter-intuitive and personally I find it extremely ugly. The point is to get the compiler to throw an error when you accidentally write =
instead of ==
, but good compilers have an option to warn you about this anyway so it's unnecessary.
The second version is supposed to be safer.
In case you forget one equal sign, it does not change the value of i to zero.