Re: Which kind of loop do I use, do or while?
- From: Steve O'Hara-Smith <steveo@xxxxxxxxxx>
- Date: Thu, 28 Feb 2008 10:04:07 +0000
On Wed, 27 Feb 2008 19:38:24 -0800 (PST)
Amandil <mazwolfe@xxxxxxxxx> wrote:
Hi, I was wondering if someone could give me some advice. I'm using
C, so the constructs are those of that language, but the question is
not really language specific.
In my program, I want to process either the standard input (stdin) or
the list of files on the command line. I have two ways of doing this,
and I'm asking if there is any advantage to doing it one way or the
other.
Method 1: (using C pseudo-code)
FILE *fp = stdin;
char *filename = "standard input";
do {
if (there are arguments) {
assign filename to argument, shift args over (argv
++); open file, assign fp to FILE pointer;
Check for error while opening file
If there was an error, skip to next
iteration (continue); }
} /* Otherwise there are no files: Assemble stdin
(default) */ process(filename, fp, flags);
} while (argv[0] != NULL);
The alternative method would be not to enter the loop if there are no
files:
Method 2:
int error = 0;
FILE *fp;
char *filename;
if (there are no files) {
process("standard input", stdin, flags)
} else {
This makes the intention clearer and is therefore better IMHO. The
more clearly the code expresses the intention the less likely it is to
contain mistakes and the easier it is to read and therefore maintain.
Noting of course that sometimes clarity must be sacrificed for efficiency
but this should only be done when there is a clear need to do so.
I would be inclined even to exit after processing stdin - or
even return process("standard input", stdin, flags) - instead of using an
else but others would object on the grounds that there should only be one
exit (or return) - this is a religious matter :)
--
C:>WIN | Directable Mirror Arrays
The computer obeys and wins. | A better way to focus the sun
You lose and Bill collects. | licences available see
| http://www.sohara.org/
.
- Follow-Ups:
- Re: Which kind of loop do I use, do or while?
- From: Amandil
- Re: Which kind of loop do I use, do or while?
- References:
- Which kind of loop do I use, do or while?
- From: Amandil
- Which kind of loop do I use, do or while?
- Prev by Date: Re: strlen(), K+1: clarification
- Next by Date: Re: EXE at server
- Previous by thread: Re: Which kind of loop do I use, do or while?
- Next by thread: Re: Which kind of loop do I use, do or while?
- Index(es):
Relevant Pages
|