1

What are the pros and cons of the two following notations?

if (a == 0) ...

and

if (0 == a) ...

The first one is more readable. What about the second one?

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 1
    [More readable the second one is.](http://blog.codinghorror.com/content/images/uploads/2012/07/6a0120a85dcdae970b0176169611b8970c-800wi.png) – Kerrek SB Jun 18 '15 at 15:29
  • 3
    The second one is also known as a Yoda condition see [What is the difference between if (NULL == pointer) vs if (pointer == NULL)?](http://stackoverflow.com/q/22106713/1708801) as I note in my answer there for modern compiler this should not be needed anymore. – Shafik Yaghmour Jun 18 '15 at 15:29

1 Answers1

4

There are really only two things at play here:

First is readability, which is self explanitory.

The second is to prevent possible bugs, in your example, it prevents accidentally doing

if (a = 0)

Some compilers will warn you that you are using the implicit truthiness of the return value of an assignment, but much of the time this is a typo. If you reverse this

if (0 = a)

it won't even compile, so it is a forced prevention of the bug

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218