9

In one C++ coding style guide, I found one particular recommendation (page 41, recommendation number 53):

Always have non-lvalues on the left side (0 == i instead of i == 0).

And I don't uderstand what is this good for? Are to sticking to this practice?

I'm not and I don't know why is his a good practice. The only advantage I can think of is that is will avoid mistaking an unintentional assignment with a comparison (if (foo = 0){} versus if (foo == 0){})

Have you got any other ideas why should I use it?

Novellizator
  • 13,633
  • 9
  • 43
  • 65
  • 1
    I don't use that. It has been many years since I've made a =/== error. Experience and skill have been a better countermeasure for me than awkward expressions like Yoda Condition. Your decision to use or to not use should be based on whether you like it, whether you feel it helps you, and whether your project's coding standard forbids or requires it. – Amardeep AC9MF Apr 09 '12 at 17:00
  • 2
    The advantage of `(0 == i)` is that it can catch some `=` vs. `==` errors. The disadvantage is that reading it makes my eyes bleed. – Keith Thompson Apr 09 '12 at 17:50

2 Answers2

14

Yes, you guessed it right. It's the good, old Yoda condition!!!

enter image description here

LastBlow
  • 617
  • 9
  • 16
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 2
    Most. Awesome. Link. Ever. Love the "Egyptian Brackets!" – André Caron Apr 09 '12 at 17:00
  • lol! :) I'm googling on this and I like this jargon. Too bad the original stackoverflow pool's been deleted. Anyways, how often is the Yoda condition used? Is majority or minority of programmers using it? – Novellizator Apr 09 '12 at 17:05
  • @Tomy: Purely a matter of choice, and you won't get a definite answer to that Q.Personally i use it only of the coding guidelines of the co. or the project I work for stipulate it. – Alok Save Apr 09 '12 at 17:07
3

As you say, the reason some people use it is to occasionally avoid typing = when they mean ==.

Since it only catches some cases, where you're comparing a lvalue with a constant or rvalue, and every compiler I know of will warn you if you make that mistake, there's very little point in doing it.

At least to native English speakers, it makes the code read as if it's written backwards; so a "Yoda condition" some call it do. Like many rules in corporate style guides, it dates back to a time when dealing with unforgiving compilers was a higher priority than writing readable code.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644