Pros and cons of: (a == 0) vs (0 == a)

716 views Asked by At

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?

1

There are 1 answers

0
Cory Kramer On BEST ANSWER

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