`if (a = b)' (was Standard indentation?)
Doug Gwyn
gwyn at smoke.BRL.MIL
Wed Dec 14 15:57:13 AEST 1988
In article <1683 at valhalla.ee.rochester.edu> badri at valhalla.ee.rochester.edu (Badri Lokanathan) writes:
>I am missing something here. Why is
>a = expr; if (a == b) {statement}
>preferable, in general, to
>if ((a = expr) == b) {statement}
Writing a whole bunch of unrelated actions on the same line of text isn't
particularly readable no matter what the actions are. Try
a = expression;
if ( a == b )
statement
There are several principles of style that apply to coding. One that is
relevant here is:
Actions that are thought of as separate tasks
should be separated visually.
If setting the value of `a' is conceptually only loosely related to
determining whether `a' now matches `b', then it is better to visually
separate these actions. On the other hand, if they are best thought
of as closely coupled, then combining them is appropriate:
for ( p = &qhead; (p = p->link) != &qhead; )
/* operate on node *p */
Sometimes, as in this example, it's really a "judgement call".
for ( p = qhead.link; p != &qhead; p = p->link )
/* operate on node *p */
is just about as acceptable. However, the following is poor:
p = qhead.link;
while ( p != &qhead )
{
/* operate on node *p */
p = p->link;
}
C's "for" statement was designed for bringing together visually
all the parts of loop control; use it for that. (A recent posting
showed a "for" statement whose three parts were not all involved
in controlling the loop; that violates the stylistic principle I
gave above.)
I agree with the recommendation that programmers read "The Elements
of Programming Style" by Kernighan and Plauger. There are other
books that give good stylistic advice, but that's the best starter.
Incidentally, this book doesn't use C in its examples, but the
principles are valid for most programming languages.
There isn't any way to automate good programming style, any more
than there is any good way to guarantee good program design.
Careful thought is essential.
More information about the Comp.lang.c
mailing list