Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!amdahl!amdcad!tim From: tim@amdcad.AMD.COM (Tim Olson) Newsgroups: comp.unix.questions Subject: Re: Wierd Compilers Message-ID: <18964@amdcad.AMD.COM> Date: Mon, 2-Nov-87 12:32:45 EST Article-I.D.: amdcad.18964 Posted: Mon Nov 2 12:32:45 1987 Date-Received: Thu, 5-Nov-87 23:40:17 EST References: <367@white.gcm> Reply-To: tim@amdcad.UUCP (Tim Olson) Organization: Advanced Micro Devices Lines: 55 Keywords: Sun In article <367@white.gcm> dc@gcm (Dave Caswell) writes: | /* Program 1 */ | main() | { | int i = 500000; | | while(--i); | } | | /* Program 2 */ | main() | { | int i = 500000; | | while(i--); | } | | Does anyone have a guess why program one runs in half the time of program two? | BTW this is a SUN 3. Questions like this are easily answered by examining the assembly-language generated by the compiler. The difference is due to the semantics of post-decrement vs pre-decrement. The post-decrement operator returns the value of i *before* it is decremented, while the pre-decrement returns the value of i *after* it is decremented. The post-decrement compiles to something like: movl #50000,a6@(-4) .L13: movl a6@(-4),d0 ; copy the old value subql #1,a6@(-4) ; now decrement i tstl d0 ; is the old value zero? beq .L14 bra .L13 .L14: While the pre-decrement compiles to: movl #50000,a6@(-4) .L15: subql #1,a6@(-4) ; decrement i beq .L16 ; is it zero? bra .L15 .L16: This is yet another reason to use pre-decrement over post-decrement when all that is wanted is the side-effect of decrementing, and the return value is thrown away. -- Tim Olson Advanced Micro Devices (tim@amdcad.amd.com)