Always use braces (was: Suggested new C loop syntax)
Piercarlo Grandi
pcg at aber-cs.UUCP
Tue Jan 3 03:50:41 AEST 1989
In article <11037 at ulysses.homer.nj.att.com> cjc at ulysses.homer.nj.att.com (Chris Calabrese[mav]) writes:
# In article <271 at twwells.uucp>, bill at twwells.uucp (T. William Wells) writes:
# > In article <8 at estinc.UUCP> fnf at estinc.UUCP (Fred Fish) writes:
# > ...
# > : I was recently helping out a freshman CS major with her C homework and
# > : found out, to my horror, that the teacher in the course was marking
# > : off points for code which included braces when they weren't strictly
# > : required. They were teaching her to write code like:
# > :
# > : inchar = getchar ();
# > : while (inchar != EOF)
# > : if (inchar == 0)
# > : goto done;
# > : else
# > : inchar = getchar ();
# > : done: return inchar;
# > :
# > : Ickkk!!!
# >
# > Double Ickkkk!!!! A goto where a break would have done.
# This is yet another tripple icky example of CS professors
# thinking that just because they can get the example programs
# in K&R to compile, and because they did work in Fortran in
# their thesis on astrophysics, they are qualified to teach
# C (or any other language). Wrong, wrong, wrong.
#
# Any C guru qualified (in my humble opinion) to teach
# C would be trying to teach code which looks like:
#
# /*
# * assume students have not learned the ',' operator yet
# */
# do {
# inchar = getchar();
# } while(inchar != EOF && inchar);
# return inchar;
#
# Personally, I haven't decided whether the while should be lined
# with the do or the loop body yet, but I like the brace alignment
# this way.
I would beg to suggest the following for the loop:
for
(
inchar = fgetc(stdin);
inchar != EOF && inchar != '\0';
inchar = getc(stdin)
);
Just to make it evident that this is a sequential scan. I use fgetc(3) to
initialize inchar because it does not get expanded inline (unless of course
I knew that in most cases the loop would be exited immediately)..
The following solution is more compact and arguably more in the C tradition,
but I think that making explicit the iteration structure with a for(;;) and
the explicit test against '\0' are somewhat more readable.
while ((inchar = getchar()) && inchar != EOF);
--
Piercarlo "Peter" Grandi INET: pcg at cs.aber.ac.uk
Sw.Eng. Group, Dept. of Computer Science UUCP: ...!mcvax!ukc!aber-cs!pcg
UCW, Penglais, Aberystwyth, WALES SY23 3BZ (UK)
More information about the Comp.lang.c
mailing list