5

I have a basic question, which is bugging me a lot and I am unable to figure out why a programmer uses it.

if (0 == Indx)
{ 
    //do something
}

What does the above code do and how is it different from the one below.

if (Indx == 0)
{
    // do something
}

I am trying to understand some source code written for embedded systems.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jesh Kundem
  • 960
  • 3
  • 18
  • 30
  • 2
    http://c-faq.com/style/revtest.html – David Ranieri Nov 07 '16 at 21:54
  • 1
    It's [Yoda notation](https://en.m.wikipedia.org/wiki/Yoda_conditions) – nakano531 Nov 07 '16 at 21:57
  • 3
    That's called a Yoda conditional. It was useful to write conditions that way back in the 1980's because the compilers wouldn't give you a warning if you accidentally wrote `if (Indx = 0)`. Nowadays, every decent compiler will give you a warning, so Yoda conditionals have fallen out of style. Of course, as always, old ideas never die, only their supporters do. – user3386109 Nov 07 '16 at 21:58
  • My brain scans `if(0<=some_long_call(arg0,arg1,arg2,subcall(subarg0,subarg1)))` slightly quicker than `if(some_long_call(arg0,arg1,arg2,subcall(subarg0,subarg1))>=0)`. Yoda, I speak, because used to optimizing milliseconds I am. – Petr Skocik Nov 07 '16 at 22:23
  • Possible duplicate of [How to check for equals? (0 == i) or (i == 0)](http://stackoverflow.com/questions/148298/how-to-check-for-equals-0-i-or-i-0) – Salman A Nov 08 '16 at 08:04

1 Answers1

8

Some programmers prefer to use this:

if (0 == Indx) 

because this line

if (Indx == 0)

can "easily" be coded by mistake like an assignment statement (instead of comparison)

if (Indx = 0) //assignment, not comparison.

And it is completely valid in C.

Indx = 0 is an expression returning 0 (which also assigns 0 to Indx).

Like mentioned in the comments of this answer, most modern compilers will show you warnings if you have an assignment like that inside an if.

You can read more about advantages vs disadvantages here.

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
  • 2
    This is one of those things that just would not die. Modern compilers issue a warning for this. Take advantage of it. –  Nov 07 '16 at 21:57
  • @Arkadiy I've never expressed my personal opinion on this, I may agree or not with you. I'm just trying to answer the question, which is "I am unable to figure out why a programmer uses it?" – Cacho Santa Nov 07 '16 at 21:58
  • I never said anything about your personal opinion either :). Could you please mention the more modern approach as well? –  Nov 07 '16 at 22:00
  • @Arkadiy Visual Studio doesn't warn about it unless you use `/W4` or `/Wall`. – Barmar Nov 07 '16 at 22:05