Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If (Rvalue == LValue)

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?

like image 759
KurtisLininger Avatar asked Apr 20 '12 19:04

KurtisLininger


Video Answer


3 Answers

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.

like image 169
k06a Avatar answered Oct 07 '22 10:10

k06a


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.

like image 2
xbonez Avatar answered Oct 07 '22 12:10

xbonez


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.

like image 1
Sergey Podolsky Avatar answered Oct 07 '22 12:10

Sergey Podolsky