home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!destroyer!ubc-cs!unixg.ubc.ca!lermer
- From: lermer@theory.chem.ubc.ca (Noah Lermer)
- Subject: Loop structures
- Message-ID: <1992Jul24.003402.9071@unixg.ubc.ca>
- Sender: news@unixg.ubc.ca (Usenet News Maintenance)
- Nntp-Posting-Host: theory.chem.ubc.ca
- Organization: University of British Columbia, Vancouver, B.C., Canada
- Date: Fri, 24 Jul 1992 00:34:02 GMT
- Lines: 77
-
- Hello everyone,
-
- I've got a loop flow problem.
-
- I read a value from the user
- Check that the value is valid,
- if it is then I just want to continue,
- if it is not, then I display an error and reprompt for the value.
-
- in pseudocode:
-
- :loop
- get input <---------
- if (!valid) |
- complain to user |
- then loop: -------
-
- The problem comes when I want to code this in C
- I've found a couple ways of doing this, none of which I like completely.
-
- Solution i)
-
- do {
- ... get input ...
- } while ( !valid ? showerror(),1 : 0 );
-
- The obvious problem with this is that it is ugly and hard to read,
- let alone maintain, but could be ok if you macro-ised it.
-
- Solution ii)
-
- :label
- .... get input ...
- if (!valid)
- {
- showerror();
- goto label;
- }
-
- Aside from the religious issues involved, using a goto in this situation
- can also get hairy to look at since I need several inputs one after another
- (all with their own set of labels etc...) separated by a fair bit of code
- from the goto (the get input section can be fairly long). It gets easy to
- loose track of which label goes with which code block, especially if they
- are nested (ie, parts of one input are validated individually as well).
- On the other hand, it is easily extensible to multiple error conditions.
-
- Solution iii)
-
- do {
- ... get input ...
- if (valid)
- break;
- showerror();
- } while(1);
-
- This is the solution I like the most, but has the disadvantage (like i) that
- multiple error conditions are not handled easily. This should also be easy to
- macro-ise.
-
- Some more comments:
- The (valid) or (!valid) condition is a rather complicated arithmetic expression
- I would prefer to only have to calculate once. At the moment I have only one
- error condition, but as a general algorithm, I would prefer to be able to
- handle different types of errors.
-
- For what it's worth, the input routines are not from the standard library.
- I'm doing direct screen i/o on a PC, so any technique you suggest should not
- make any assumptions about <stdio.h>
-
- I'd really appreciate any comments/suggestions (/flames :) you
- care to send my way. E-mail (hollebon@cemaid.chem.ubc.ca or
- lermer@theory.chem.ubc.ca) and I'll summarise for the 'net.
-
- Thanks for your time,
- Bruce Hollebone,
- hollebon@cemaid.chem.ubc.ca
-