Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for using '5 == myValue' in conditionals [duplicate]

Tags:

c++

I've come across some code that flips how a condition is checked and was wondering why this would be done aside from a weird personal quirk. I've never seen any text books use it nor have I seen any sample code done this way.

// why do it this way?
if (5 == myValue) 
{
    // do something
}

// instead of:
if (myValue == 5) 
{
    // do something
}

I've only seen this way for == operand but not for any other operands.

like image 570
Willam Hill Avatar asked Nov 26 '13 17:11

Willam Hill


2 Answers

Some people like doing that because if you mess up and type a single-equals instead of a double-equals, "if (val = 5)" is only a compiler warning, while "if (5 = val)" is an error (you can't assign to a constant).

I think it's sort of ugly, personally, and that you should be checking your warnings just as much as your errors, but that is the reason for that convention (which is thankfully not universal, but is at least moderately widespread. It is also true that it might not universally have been treated as even a warning by much older compilers, and this convention has been around for a long time.)

Fun fact: I was just reading Code Complete (Second Edition), and Steve McConnell agrees with me, stating his personal preference is "to use number-line ordering and let the compiler warn me about unintended assignments". Steve McConnell by definition knows what he's talking about.

like image 187
neminem Avatar answered Oct 26 '22 18:10

neminem


Some folks do it for readability when myValue is deemed less interesting than 5; it puts the constant value in a more prominent place. There is no practical reason for it - purely a judgment call on the part of the coder.

like image 32
Mike Woolf Avatar answered Oct 26 '22 18:10

Mike Woolf