Last Updated: October 07, 2020
·
732
· punksteez

Good Habits: Compare the Constant First

One of those bugs that affects newbs and (perhaps with decreasing frequency) the old guard alike is the accidental slip of the key on the second '=' in what was supposed to be a equality comparison.

If, for example you want to check the following:

if( v == 1 )
{
    ...
}

But you're typing in a flurry because your idea will revolutionize the industry and you accidentally do this:

if( v = 1 )
{
    ...
}

Guess what? - totally valid! Now you've got a case of "always true" and you've corrupted the value of 'v' for good measure. Get ready to spend the next 3 hours trying to figure out how everything got so messed up.

But, if you get into the habit of doing this:

if( 1 == v )
{
    ...
}

And you make the same mistake...

if( 1 = v )
{
    ...
}

...the compiler will complain right away and easily catch the bug before you spend hours debugging your code.

1 Response
Add your response

One can also just use a good compiler - gcc will warn about this (-Wparentheses, in -Wall).

over 1 year ago ·