From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 19621 invoked by alias); 17 Dec 2009 16:51:11 -0000 Received: (qmail 19606 invoked by uid 22791); 17 Dec 2009 16:51:09 -0000 X-SWARE-Spam-Status: No, hits=-1.3 required=5.0 tests=AWL,BAYES_00,SPF_SOFTFAIL X-Spam-Check-By: sourceware.org Received: from xena.cds1.net (HELO mail.cds1.net) (216.174.197.150) by sourceware.org (qpsmtpd/0.43rc1) with ESMTP; Thu, 17 Dec 2009 16:51:05 +0000 Received: from [192.168.1.100] (unknown [192.82.28.137]) by mail.cds1.net (Postfix) with ESMTP id D00A5E8A277B; Thu, 17 Dec 2009 08:50:36 -0800 (PST) Subject: Re: Could you please explain this code segment From: Bob Plantz To: "W.H. Kalpa Pathum" Cc: gcc-help In-Reply-To: <79fa0d5a0912162253p49d17f36s2e65d4be8394df69@mail.gmail.com> References: <79fa0d5a0912162253p49d17f36s2e65d4be8394df69@mail.gmail.com> Content-Type: text/plain; charset="UTF-8" Date: Thu, 17 Dec 2009 17:04:00 -0000 Message-ID: <1261068623.2170.13.camel@bob-desktop> Mime-Version: 1.0 Content-Transfer-Encoding: 7bit X-IsSubscribed: yes Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2009-12/txt/msg00257.txt.bz2 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