Cryptic code == Optimized code ? YES : NO ;
Stephen P Spackman
stephen at estragon.uchicago.edu
Tue Sep 11 11:53:36 AEST 1990
In article <861 at gtenmc.UUCP> csp at gtenmc.UUCP (Charudutta S. Palkar) writes:
C is a very good language ie to say it good to good programmers and
bad to bad programmers.
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;
C is daft. Why do extra work? a and b differ in intent; if you are
thinking? "Hmm. Next step, set k to the right value", use b; if you
are thinking "Well, there are two cases, and k will have to be
different in each case...", maybe you want a.
In short: think about what will happen when you need to *modify* the
code, and code accordingly.
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;
Use {int /* Or whatever */ tmp = a; a = b; b = tmp;}
Moves are faster and clearer. Why do extra work?
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;
Never do bit arithmetic on signed types. And isn't this the same as (2)?
Example 4: Variables a and b are pointers to structures with
self referential pointers as fields.
typedef struct fool
{
struct fool *nxt , *prv;
char data;
} node , *ptr;
ptr a, b;
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;
(b) could mean almost anything. Use a.
The functions of examples 2 & 3 is to interchange values 2 variables
of numeric type. Example 4 is insertion of a node in a circularly
doublely linked list.
My questions are :
1 ) Will the code generated by a non-optimizing comiler be more
more optimised as a set of statements get combined into one
expression.
No. Probably the reverse.
2 ) Will the same happen even with an optimizing compiler.
No. It will make *no* difference, one hopes.
3 ) Should such kind of compaction be favoured for development.
No. See comments above. In fact, the "obvious" versions are more
obvious to the compiler, as well as to humans.
My question is, did I just fall for a joke? Remember, people will
spend longer maintaining your code than the computer will running it.
And people are more valuable than computers.
stephen p spackman stephen at estragon.uchicago.edu 312.702.3982
p.s. Have you considered writing crossword puzzles?
More information about the Comp.lang.c
mailing list