Unnecessary Assignments
From Software By Jeff
Occasionally changing code results in ugly code. Someone goes to some length to do what they believe is a correction, but in fact results in stupid remains, quite often with catastrophic results.
This tidbit was passed on by someone else, but I felt compelled to comment on it.
var = var++;
This code could be C, C++, Java, PERL, PHP, or a variety of other languages. The double-plus operator is, of course, an incrementer. In this case, a post-increment.
At first glance, it may look to the casual observer or the lesser skilled as an increment and redundant assignment. Knowing a little about the order of operations, we know that the assignment (the equals sign) will happen last, so the other operation will happen first. The right half of the equals sign will change the value of var by incrementing by one. Then the equals sign will take that value and assign it to var by itself. Seems simply like a redundant assignment.
The key to remember, though, is the operation is a post-increment. What that means is that the value of var is incremented by one (so 9 becomes 10), but the result of the operation is to return the previous value of var (in the previous example, returns 9). What happens next is that previous value of var is again assigned to var. This very quickly negates the incrementation.
What probably happened is that the developer passing through this saw code similar to this.
var = var + 1;
That developer probably thought the double-plus operator would be better suited for the job, which any one who's been working in these languages for a while would agree. The quick-fix simply replaced the "plus one" with "plus plus" and removed some seemingly extraneous spaces, resulting in the code on which I'm commenting.
What this code-cleaner did wrong was fail to remove the assignment. Since the operator chosen was a post-increment, as mentioned above, the assignment negates the increment, turning the code instead to the following.
var = var;
Or, as allowable pretty much only in C or C++, the code became simply.
var;
A lesser evil, but still with an unnecessary assignment, would have been to use the pre-increment operator instead.
var = ++var;
This would (likely correctly) increment the value of var, and return the new value. Then the unnecessary assignment would happen and the same value would again be assigned to the variable.
What the code-cleaner undoubtedly intended instead was simply this.
var++;
In this case, it doesn't matter whether the post- or pre-increment operator is used as the result of the operation is simply ignored. This means the following is equally valid.
++var;
So, is the moral to always pre-increment? Absolutely not. There are plenty of cases where the operation order matters greatly. Many more cases where the order does not matter. The key is to be aware of the operator precedence and results of each operator in a chain of events.