Reputation: 258
IS there a difference between these two conditions:
if (a==5)
and if (5==a)
?
Upvotes: 1
Views: 90
Reputation: 2847
If 'a' points to an object that overrides ==, then you may get different results in theory.
Upvotes: 1
Reputation: 490048
The two are normally the same.
Some people recommend putting the constant first (if (5==a)
) because this way, if you mis-type and leave out one of the =
to get: if (5=a)
, the compiler will give an error message, whereas if (a=5)
will compile and execute, but probably not do what you want.
Some compilers will give a warning for the latter (e.g., recent iterations of gnu do) but others don't (and Visual C++ is among the latter).
Upvotes: 1
Reputation: 181270
No, there is no difference at all.
People used to write this expression 5==a
instead of a==5
so the could catch a=5
errors on C/C++ where that expression is perfectly valid and always evaluates to true
. That way, if programmer writes (by mistake) the expression 5=a
then it will get a compiler error.
Upvotes: 1