There are certain programming language features that my Principles of Programming Languages professor disapproves of. For instance, in C (and, to a slightly lesser extent, Java), the operator
==
is used to compare two things. For instance,
if (a == b) {
(do something)
}
will do the something if a is equal to b, and not otherwise. On the other hand, the operator = sets one value to be equal to another. For instance,
a = b
will take the value in b and store it in a.
However, the
=
operator also returns the value of b, so if you want to be clever, you can do something like
if (a = b) {
(do something)
}
This sets a equal to b
and does something if b was true. Unfortunately, it also leads to rampant errors, because when people type
if (a = b)
they almost always meant
if (a == b)
, and if
=
did not return a value, then the compiler would let you know you were making a mistake.
So, my professor is against using
=
in an
if
statement; it's the kind of clever thing that leads to mistakes. He also inveighs against things like using the
++
operator in an expression. If you write
a++
it will increment a by 1 (so it is the same as
a = a + 1
). No problem there.
++a
does the same thing. But where they are different is that they each return a value, but
++a
increments a before returning it, and
a++
increments it after returning. So that if I said something like
if (k++ == 3)
I would be saying "If k is equal to three (and, by the way, after you do that, increment k by 1)..", but if I wrote
if (++k == 3)
I would be saying "Increment k, then if it's equal to 3..."
Clever! It saves you a whole line of code, and makes your code harder to maintain and more error-prone at all once!

A guy in my class (who looks like a young, evil Vincent D'Onofrio) argued back, saying that he always uses such methods when possible. He argued that anyone who knows the language should be able to read a statement like
if (a = ++k)
so that he is not worried that it won't be understood. He doesn't work with CS1 students, after all. Someone who wouldn't understand these basic language features is worthy only of contempt, he suggested.
What I think he's missing is that maintenance makes up most of the costs associated with code, and every time that it takes someone 10% longer to read a line of your code, or even 5% more likely to make an error in maintaining it (not to mention your own increased chances of error in writing it), it un-pays for itself. And what was the benefit to begin with? Occasionally getting to skip some typing? Feeling clever by combining statements?
I think it's foolish.