If (Rvalue == LValue)
Asked Answered
O

3

6

This is just out of curiosity I ask...

99% of the code I see anywhere, when using "IF", will be of the format "If (RValue == LValue) ...". Example:

If (variableABC == "Hello World") ...

There are other examples where I see the opposite:

If ("Hello World" == variableABC)

Anyone know how this started and why it's done?

Outboard answered 20/4, 2012 at 19:14 Comment(2)
Since what is happening here is an equality test, it doesn't really matter which value is on either side of ==, since if a == "b" then "b" == a must also be true. I imagine the first scenario is done to prevent assignment when the you use = instead of == on accident.Secrecy
These expressions are called "Yoda Expressions", see wiert.me/2010/05/25/…Mutism
K
3

It is done because of this mistake in C and C++:

if (variableABC = "Hello World") ...
                ^
                (Watch here)

This way we have a compilation error:

if ("Hello World" = variableABC)
                  ^
                  (Watch here)

For example, C# and Java languages don't need this trick.

Knell answered 20/4, 2012 at 19:16 Comment(1)
Amazing: before I am allowed to mark the answer, there's already 3 answers.Outboard
B
2

The latter is done to prevent unintended assignments, if you, by mistake, use the assignment operator = instead of the equality operator =='

Some languages do not allow an assignment in an if-condition, in which case either is fine.

In languages that do accept assignments in if conditions, I always prefer going with the latter case.

Bousquet answered 20/4, 2012 at 19:16 Comment(0)
J
1

This is done because of the errors developers often do writing = instead of ==. In C++ integers can be treated as booleans and you got no errors at compile time.

Jameljamerson answered 20/4, 2012 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.