Jesh Kundem
Jesh Kundem

Reputation: 974

Why use if condition (0 == Indx) instead of (Indx == 0) — is there a difference?

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.

Upvotes: 5

Views: 122

Answers (1)

Cacho Santa
Cacho Santa

Reputation: 6914

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.

Upvotes: 8

Related Questions