C bites / programming style [if (cond); statement;]
Roy Smith
roy at phri.UUCP
Mon Aug 26 05:11:01 AEST 1985
> I avoid getting bitten in this way by ALWAYS using {}'s after
> if, while, etc. Even when I have a null statement as the body [...]
> -Michael Shannon (hplabs!oliveb!3comvax!mikes)
Since I was the original poster of this particular bite, let me
add a few random comments. First off, I'm really kind of amazed how much
discussion this is getting. I wish people would pay this much attention
when I do things correctly!
Oddly enough, part of the bite was from emacs. Since the code in
question was repeated several times with small changes, I wrote it once and
used a macro to duplicate and modify it each time. My real goof was in
defining the emacs macro. I somehow dragged the extra semi-colon along
causing an error I probably wouldn't have made if I wrote each fragment by
hand. Shows me to try and be clever.
I put null loop-bodies on a separate line like in the following
example. You all know how I write null if-bodies. :-)
while (eatup() != '\n')
;
If the body of the [whatever] is a single simple statement, I leave
out the braces and do something like the following (I'm using "simple" in
the generic sense, not strictly as defined by the C grammer):
if (foo >= bar) | while (*foo++ == bar)
sum += foo; | printf ("still a bar\n");
else |
toosmall++; |
If the body is more complicated than an assignment or function
call, I put it in braces, even though they really aren't needed, thus:
while ((foo = getfoo()) != EOF) |
{ | for (x=0; x <= 10; x++)
if (foo >= bar) | {
sum += foo; | for (y=0; y <= 10; y++)
else | sumxy += x * y;
toosmall++; | }
} |
The entire "if-else" or "for" construct is a single statement, but
intuitively I think about lines and statements being the same (probably a
holdover from my Fortran days). If I write a multi-line statement, I put
braces around it to make that clear (to myself, if nobody else). Actually,
in the "for" example above, I would probably drop the braces. If, however,
the inner loop needed braces, the outer one would be sure to get them too.
A few people have suggested I run my source through a code grinder
like "cb". If the output of cb is different from its input, it's a hint I
goofed somewhere. Something like "cb < foo.c | diff foo.c -" would do the
job nicely. While this is a good idea, I don't see why this isn't built
into "lint".
OK, now can we please start working on somebody else's boo-boos?
It's embarrassing to see my dirty laundry come back at me 6 times a day,
even if it is somewhat amusing.
--
Roy Smith <allegra!phri!roy>
System Administrator, Public Health Research Institute
455 First Avenue, New York, NY 10016
More information about the Comp.lang.c
mailing list