Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!rutgers!gatech!hubcap!ncrcae!ncrlnk!uunet!mcvax!ukc!dcl-cs!aber-cs!pcg From: pcg@aber-cs.UUCP (Piercarlo Grandi) Newsgroups: comp.lang.c Subject: Re: Always use braces (was: Suggested new C loop syntax) Message-ID: <474@aber-cs.UUCP> Date: 2 Jan 89 17:50:41 GMT Reply-To: pcg@cs.aber.ac.uk (Piercarlo Grandi) Distribution: eunet,world Organization: CS Dept., University College of Wales, Aberystwyth, UK (Disclaimer: my statements are purely personal) Lines: 66 In article <11037@ulysses.homer.nj.att.com> cjc@ulysses.homer.nj.att.com (Chris Calabrese[mav]) writes: # In article <271@twwells.uucp>, bill@twwells.uucp (T. William Wells) writes: # > In article <8@estinc.UUCP> fnf@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@cs.aber.ac.uk Sw.Eng. Group, Dept. of Computer Science UUCP: ...!mcvax!ukc!aber-cs!pcg UCW, Penglais, Aberystwyth, WALES SY23 3BZ (UK)