What's the reasoning behind putting constants in 'if' statements first?

c++, coding-style, constants, if-statement

Solution

So that you don't mix comparison (==) with assignment (=).

As you know, you can't assign to a constant. If you try, the compiler will give you an error.

Basically, it's one of defensive programming techniques. To protect yourself from yourself.

Problem

I was looking at some example C++ code for a hardware interface I'm working with and noticed a lot of statements along the following lines: ``` if ( NULL == pMsg ) return rv; ``` I'm sure I've heard people say that putting the constant first is a good idea, but why is that? Is it just so that if you have a large statement you can quickly see what you're comparing against or is there more to it?

Original source