Quick Q: Why write "5 == myValue" instead of "myvalue == 5"? -- StackOverflow

Quick A: Because it catches most cases where you accidentally wrote = instead of ==.

From SO:

Reason for using '5 == myValue' in conditionals

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.

Add a Comment

Comments are closed.

Comments (1)

0 0

akostur said on Nov 26, 2013 10:29 PM:

This was a popular thing years ago where people would accidentally write "if (myValue = 5)", get a true result and accidentally overwrite the contents of the myValue variable. (See: Yoda Conditions). If you wrote it as "if (5 = myValue)", then the compiler would get very upset with you attempting to assign to a literal. However most (if not all) modern compilers will emit warnings when it sees an assignment where it's expecting a conditional, so it is easier to read when written as "if (myValue == 5)". (You are turning up the warnings on your compiler, right?) (Erm... posted before I read closer and saw that there was an answer right at the top... my eyes had completely skipped over it)