Lawrence said:
However this is an incomplete solution (you don't always have a non-lvalue
available) that results in less readable and less consistent code. Many
compilers will diagnose this given suitable options and there are other
"lint" tools available which will do so. This is much more relaible than
source tricks like that above and is a much better approach.
Lawrence
Absolutely, switching the left and right sides of an equality test as
it is conventionally written makes the expression less readable [until
the pattern becomes familiar]. The more readable the code, the more
likely its errors will be overlooked. "Readable" text describes text
that fits a familiar pattern, and which the brain can read faster
because it can skip many of the words by filling in their most likely
form and meaning. In this case an assignment expression can "read" like
an equality test, so the mistake can go undetected.
Note that switching the right and left operands makes the expression no
less understandable. Source code should be written to be
understandable, posts to USENET should be written to be readable. The
computer does not execute a source program as if it were reading a
novel. So a person reading the source of a program, should not read it
in the same way as they would a novel.
There are benefits to a less readable syntax even in the case when the
left hand expression is not a constant. The brain will have to scan the
expression much more closely (because it does not fit the expected
pattern), in order to parse it. And the closer scrutiny is more likely
to catch an assignment error.
The motivation to write readable code is to lighten the workload on its
reader; but it does so by essentially inviting the reader to gloss over
its mistakes. The computer executing the code will overlook no error;
so the reader should approach the source code as the computer does and
have to examine each line to understand its meaning. Because whether a
set of source code is readable or not, matters far less than whether it
is understandably correct.
Greg