Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!ncar!tank!mimsy!haven!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: `if (a = b)' (was Standard indentation?) Message-ID: <9164@smoke.BRL.MIL> Date: 14 Dec 88 05:57:13 GMT References: <1988Dec8.173158.11839@utzoo.uucp> <846@starfish.Convergent.COM> <14945@mimsy.UUCP> <1683@valhalla.ee.rochester.edu> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 55 In article <1683@valhalla.ee.rochester.edu> badri@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.