Re: Could you please explain this code segment

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.

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



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux