Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

if-statement

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.

like image 948
Jesh Kundem Avatar asked Nov 07 '16 21:11

Jesh Kundem


1 Answers

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.

like image 168
Cacho Santa Avatar answered Nov 15 '22 04:11

Cacho Santa