|
| Oliver Wong wrote:
>
> The "if (3 == x)" is an idiom in C because in C, assignment
> statements are legal. So a programmer might mistakenly type "if (x =
> 3)", which will MODIFY x (assign it the value 3) as part of the
> conditional test.
>
> If the programmer gets in the habit of putting the literal first, the
> equivalent typo would be "if (3 = x)", and the compiler would complain
> that you can't assign to a literal, thus catching the error.
>
> The Java example has the same issue as above (ordering of the terms
> being compared), but an additional one in that a lot of (beginning?)
> Java programmers don't realize that String literals are themselves
> objects, and so you can use the dereferencing operator '.' on them, and
> invoke their methods.
>
> The reason for having the literal first is to avoid a
> NullPointerException in the case where myString is null.
You know, this makes more sense than a lot of the C (and C-like)
language stuff I've seen. You're right, that it does make more sense to
says "if x = 3" than "if 3 = x". Thanks for this explanation - at least
one person here is better off for it. :)
(I knew you could change the value with a single "=" - catching it like
that is what was new to me.)
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~
~ / \ / ~ Live from Montgomery, AL! ~
~ / \/ o ~ ~
~ / /\ - | ~ daniel@thebelowdomain ~
~ _____ / \ | ~ http://www.djs-consulting.com ~
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
~ GEEKCODE 3.12 GCS/IT d s-:+ a C++ L++ E--- W++ N++ o? K- w$ ~
~ !O M-- V PS+ PE++ Y? !PGP t+ 5? X+ R* tv b+ DI++ D+ G- e ~
~ h---- r+++ z++++ ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~
"Who is more irrational? A man who believes in a God he doesn't see, or
a man who's offended by a God he doesn't believe in?" - Brad Stine
|
|