On Thu, 17 Dec 2009, Bob Plantz wrote:
On Thu, 2009-12-17 at 12:23 +0530, W.H. Kalpa Pathum wrote:
The following block of code when compiled with gcc (gcc version 4.4.2
20091027 (Red Hat 4.4.2-7) (GCC) ) resulted in the following output.
Could you please explain how the output differs (when assigned to the
variable b and in printf statement) and the way the compiler executes
each segment of the variable?
int main(){
int a = 10;
int b = (++a) + (++a);
printf("%d %d %d %d\n", b, a++, a, ++a);
printf("%d %d %d %d\n", ++a + ++a, a++, a, ++a);
return 0;
}
OUTPUT
24 13 14 14
36 15 18 18
I spent much of my life trying to convince CS students that they should
never write code like this. Not because of implementation issues, but
because it's nearly impossible for the maintenance programmer to
determine the intent of the algorithm here. And I always pointed out
that the maintenance programmer might be them in a few weeks.
I have seen many, many examples, both in industry and in academia, where
programmers write tricky code claiming it is more efficient. I claim (a)
efficiency is seldom an issue, and (b) looking at the generated assembly
language almost always shows it is not more efficient.
I believe that the best code is that which (a) correctly solves the
problem, and (b) is the most simple-minded in appearance.
Perhaps, but the code in question here is not merely obscure - it's simply
meaningless. I think it's a mistake to put such code in the same category
as e.g. an affine transform implemented in inline assembly which has
well-defined meaning. The latter may pose a challenge for a maintenance
programmer, but at least it will yield to persistence. In contrast,
undefined code is no better than a "todo" comment - you're only option is
to replace it completely with something well-defined based on the
documentation and/or context.
Thus my answer to your question is that you should rewrite the code such
that it clearly shows what you are trying to do. This example would not
have received a high grade in any of my classes.
--Bob