Re: Which kind of loop do I use, do or while?
- From: Neil <NeilKurzm@xxxxxxxxxxxxxxxx>
- Date: Thu, 28 Feb 2008 01:28:28 -0500
Amandil 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 {
while (there are files left) {
Assign filename, advance argv;
Open filename, assingn fp;
Check for error while opening file (of course);
If there are errors, skip to next iteration (continue);
process(filename, fp, flags);
}
}
I apologize if the format of the question is not proper for this
group.
-- Marty Amandil
use the do if your loop must run at least once. use a while if it may not run at least once. use a for if you know exactly how many times it will loop.
.
- 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: [ann] C/C++ interpreter Ch 6.0 released
- Next by Date: Re: strlen(), K+1: clarification
- Previous by thread: 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
|