Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!sdrc!thor!scjones From: scjones@thor.UUCP (Larry Jones) Newsgroups: comp.lang.c Subject: Re: Cryptic code == Optimized code ? YES : NO ; Keywords: compliers , optimization , development Message-ID: <168@thor.UUCP> Date: 11 Sep 90 14:20:21 GMT References: <861@gtenmc.UUCP> Organization: SDRC, Cincinnati Lines: 59 In article <861@gtenmc.UUCP>, csp@gtenmc.UUCP (Charudutta S. Palkar) writes: > Example 1: Variable k is of type int. > a ) if ( a > b ) k = 7; > else k = 5; > b ) k = a > b ? 7 : 5; > c ) k = ( a > b ) * 2 + 5; As has already been pointed out, the difference between a and b is one of emphasis -- a emphasizes the test, b emphasizes the assignment. Which to use depends on which you think is more important. c is sufficiently crytpic that I wouldn't use it; although I understand it, whoever has to maintain the code might not. > Example 2: Variables a and b are of the same type either int , char , float. > a ) a = a + b; b = a - b; a = a - b; > b ) a = a - ( b = ( a = a + b ) - b ); > c ) a -= b = ( a += b ) - b; Both b and c and invalid as they contain multiple assignments to the same variable without a sequence point. The common swap code: tmp = a; a = b; b = a; is not only more obvious, but probably faster as well. > Example 3: Variables a and b are of the same type either int , char > a ) a = a ^ b; b = a ^ b; a = a ^ b; > b ) a = a ^ ( b = b ^ ( a = a ^ b )); > c ) a ^= b ^= a ^= b; Same comments as example 2. > Example 4: Variables a and b are pointers to structures with > self referential pointers as fields. > a ) b->prv = a; b->nxt = a->nxt; > b->nxt->prv = b; a->nxt = b; > b ) ( b->nxt = ( b->prv = a )->nxt )->prv = a->nxt = b; Again, example b is invalid because of multiple assignments to the same variable without a sequence point. > 1 ) Will the code generated by a non-optimizing comiler be > more optimised as a set of statements get combined into one > expression. > 2 ) Will the same happen even with an optimizing compiler. > 3 ) Should such kind of compaction be favoured for development. Some compilers do more optimization within a single expression than across expressions, for better compilers it doesn't make much difference. In either case, the speed improvement you get from such optimization is rarely significant. Is the increased difficulty of writing the code, verifying that it's correct, and maintaining it worth a miniscule performance gain? Probably not. Certainly not if you end up writing incorrect code like you did above. ---- Larry Jones UUCP: uunet!sdrc!thor!scjones SDRC scjones@thor.UUCP 2000 Eastman Dr. BIX: ltl Milford, OH 45150-2789 AT&T: (513) 576-2070 Your gender would be a lot more tolerable if it wasn't so darn cynical! -- Calvin