[Followups should probably go to either news:comp.lang.c or to me personally.]
Circa 2002-Mar-02 23:35:26 -0800 dixit Marc Wilson:
: On Sun, Mar 03, 2002 at 01:58:56AM -0500, Jim Knoble wrote:
: > The indentation is misleading. If you *really* don't want to use
: > brackets around a single statement, i recommend this style:
:
: Well, yeah. But you shouldn't be using the brackets to cover up the poor
: coding practices (lousy indenting).
The use of brackets here:
if (blah) {
haha();
} else {
heehee();
}
doesn't "cover up" the indentation. Rather, the use of brackets makes
*explicit* what is otherwise *implicit*, i.e., which statements are
grouped with which clause of the compound 'if' statement. Putting a
single-statement if or if/else on a single line, like so:
if (blah) haha(); else heehee();
uses indentation to make *obvious* what is implicit, i.e. that each
clause contains only one statement. The braces tell the compiler (and,
incidentally, the reader) the programmer's intent, while the
single-line format tells only the reader the programmer's intent. In
most cases, it's better to use the braces than not to---it actually
*prevents* mistakes. In some cases, it's in fact necessary to use the
braces in order to avoid dangling else clauses, e.g.:
if (blah) if (haha) heehee(); else woohoo();
To whom does the else belong: the first if, or the second? One of
those dusty books on your shelf---you know, the one with the table of
operators and their precedence, and with the list of the "usual type
conversions"---tells you which one the compiler will pick, but how do
you remember that, especially when you have other languages to deal
with where the compiler or interpreter picks the other one? Better to
be explicit and tell the compiler (not to mention the reader) what you
really mean; either:
if (blah) {
if (haha) {
heehee();
} else {
woohoo();
}
}
or:
if (blah) {
if (haha) {
heehee();
}
} else {
woohoo();
}
For the same reason, using parentheses in an expression to order
operators and operands, even when operator precedence would pick the
"right" order, can be good practice (as long as it doesn't obsure the
expression). Again, it makes explicit (to both the compiler and the
reader) what the intent of the programmer is---thus helping to prevent
mistakes.
Of course, the programmer could simply make it obvious to the reader
what the precedence of the expression should be, by adding or removing
whitespace in strategic locations ... but that doesn't do anything to
prevent the *compiler* from misinterpreting the expression. See the
difference?
--
jim knoble | [EMAIL PROTECTED] | http://www.pobox.com/~jmknoble/
(GnuPG fingerprint: 31C4:8AAC:F24E:A70C:4000::BBF4:289F:EAA8:1381:1491)
msg05690/pgp00000.pgp
Description: PGP signature
