Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/5/84; site othervax.UUCP Path: utzoo!linus!philabs!micomvax!othervax!scott From: scott@othervax.UUCP (Scott Pace) Newsgroups: net.lang.c Subject: Re: C Programming Style Message-ID: <432@othervax.UUCP> Date: Thu, 25-Jul-85 11:11:58 EDT Article-I.D.: othervax.432 Posted: Thu Jul 25 11:11:58 1985 Date-Received: Sat, 27-Jul-85 00:37:57 EDT References: <418@spar.UUCP> Reply-To: scott@othervax.UUCP (Scott Pace) Organization: Philips Information Systems - St. Laurent P.Q., Canada Lines: 81 Summary: Here is one (more?) reason to use assignments inside of conditional statments which will especially appeal to those of you who like efficiency in your code! (I hope this hasn't been mentioned before). Consider the following piece of code: int a,fp; main() { if ( (fp = open("foo",0)) < 0 ) a = 1; fp = open("foo",0); if (fp < 0) a = 1; } Now, when this is compiled (VAX 780,4.1BSD) using the -S and -O flags, the following assembly code is produced: (the comments were added by me of course!!!) .data .comm _a,4 ;the 'a' variable .comm _fp,4 ;the 'fp' variable .text LL0:.align 1 .globl _main .data 1 L19:.ascii "foo\0" .text .data 1 L21:.ascii "foo\0" .text .set L14,0x0 .data .text _main:.word L14 pushl $0 ;push the second (last) parameter to open pushal L19 ;push the first parameter to open calls $2,_open ;call to open movl r0,_fp ;put returned value in fp (also setting cond. flags) jgeq L20 ;do the 'if' part movl $1,_a ;a = 1 if fp < 0 L20:pushl $0 ;push the second (last) parameter to open pushal L21 ;push the first parameter to open calls $2,_open ;call to open movl r0,_fp ;put returned value in fp (also setting cond. flags) tstl r0 ;set the cond. flags again!!! - redundant instruction jgeq L22 ;do the 'if' part movl $1,_a ;a = 1 if fp < 0 L22:ret ;exit So we can see from this that the compiler produces more efficient code when assignments are contained within a conditional such as the 'if' statment. It should be noted, however, that this is only one simple example and that the above observation may not hold true in all cases. Now, in this case one extra instruction isn't going to make any difference but there may be other cases where the 'if' statment is inside a loop and the loop body is executed thousands of times. This extra instruction could mean a few extra seconds (or more!) which may be critical in certain applications. One final note, the compiler does NOT generate the extra instruction when fp is declared as a register variable. It doesn't matter if fp is declared auto or static or extern, all these types generate the extra instruction except for a register declaration. What we need is a good optimizer!!! (do I get a prize for stating the obvious??!!) Scott Pace, Philips Info. Sys. Ltd., Montreal. ...!philabs!micomvax!othervax!scott