1

Possible Duplicate:
Is there a difference between i==0 and 0==i?

What's the benefit of the following coding styles , is there any difference between them ?

int i;

// more code



if (i == 0) {...}

vs

if (0 == i) {...}

Thanks

Community
  • 1
  • 1
Jack cole
  • 447
  • 2
  • 8
  • 24

3 Answers3

3

No difference at all.

I've always found the latter example less readable, and I rarely see it, but some folks seem to like it.

pb2q
  • 58,613
  • 19
  • 146
  • 147
2

No difference, pick one and stick with it for consistency. The (value == variable) is a relic from older languages where you could accidentally assign a value to a variable in an if (a = 0), instead of (a == 0)

They will both turn into (effectively) the same machine instruction, so there won't be any performance difference at all

Oleksi
  • 12,947
  • 4
  • 56
  • 80
  • It's not possible to assign a value in an if statement in Java? – OmnipotentEntity May 22 '12 at 00:31
  • @OmnipotentEntity The question is also tagged as 'c' – JRaymond May 22 '12 at 00:32
  • So it is! In that case this answer is wrong, specifically this part: `is a relic from older languages where you could accidentally assign a value to a variable in an if (a = 0), instead of (a == 0)` – OmnipotentEntity May 22 '12 at 00:32
  • @OmnipotentEntity you're right, but in C and C++ it is possible, so this convention was used there. The convention migrated to other languages, even though it wasn't needed. Most modern compilers will give you a warning about this now anyway, but it's definitely a code-style issue, and not a performance one. – Oleksi May 22 '12 at 00:33
  • It was a legit question, because I was under the impression that it IS possible to assign in an if statement in Java. And I found the implication that it wasn't possible to do that in Java to be surprising, but I wasn't totally sure, so I asked first. :) – OmnipotentEntity May 22 '12 at 00:34
  • Modern compilers, even for C and C++, will give compile warnings on accidental assignments like that. (Clang specifically comes to mind; gcc -Wall does it, too.) – Louis Wasserman May 22 '12 at 00:35
  • @OmnipotentEntity - so did you try it **before asking**??? – Stephen C May 22 '12 at 02:05
2

There's no difference in efficiency, but this style is preferred for readability:

if (i == 0) {...}

The other version, if (0 == i) {...} is an example of a Yoda condition, and it's considered a bad programming practice. Quoting from the link:

"Yoda Conditions"— using if (constant == variable) instead of if (variable == constant), like if (4 == foo). Because it's like saying "if blue is the sky" or "if tall is the man".

enter image description here

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386