[comp.lang.c] Awkward control structure

davidsen@steinmetz.ge.com (William E. Davidsen Jr) (02/24/89)

I have recently been working with a program in which none of the
existing C control structures fit the problem well. Not that the problem
isn't soluble, just that it results in messy code. Perhaps there's a
better way than either of the two I've found.

The simplified problem is that on entering this code, the user may be a
new user who has not specified a password for the data file, or may have
to give the password in order to access the file. If a new password must
be specified, the request for password should be repeated until the user
provides one which is valid in terms of complexity.

  What this started out as was this:
	if (!valid_pwd) {
	  do {
	    ask for password
	  } while (!valid_pwd);
	}
	else {
	  confirn password
	}

  What I would like to do to avoid repeating the test, if to have the
while statement allow an else clause, executed only if the while loop
were execute zero times. Then I could write:
	while (!valid_pwd) {
	  ask for password
	}
	else {
	  validate password
	}

  An alternative solution would be:
	gotvalid = TRUE;
	while (!valid_pwd) {
	  gotvalid = FALSE;
	  do {
	    ask for password
	  } while (!valid_pwd);
	}
	if (gotvalid) {
	  validate password
	}

  Or, more simply with a goto:
      UglyLabel:
	if (!valid_pwd) {
	  ask for password
	  goto UglyLabel;
	}
	else {
	  validate password
	}

  The object of this is not to ask the user to type a new password once
to set it, once to confirm you have it right, and then once again to
validate it. Twice is enough, particularly over a noisy phone line!

  Hopefully a discussion of possible language extensions will be kept
around for the next standards committee.
-- 
	bill davidsen		(wedu@ge-crd.arpa)
  {uunet | philabs}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me

bobmon@iuvax.cs.indiana.edu (RAMontante) (02/25/89)

davidsen@crdos1.UUCP (bill davidsen) <13233@steinmetz.ge.com> :
-	[ ... ]
-
-  Or, more simply with a goto:
-      UglyLabel:
-	if (!valid_pwd) {
-	  ask for password
-	  goto UglyLabel;
-	}
-	else {
-	  validate password
-	}
-
-  The object of this is not to ask the user to type a new password once
-to set it, once to confirm you have it right, and then once again to
-validate it. Twice is enough, particularly over a noisy phone line!


(I'm not convinced that this goto example won't ask the new-user to
validate the password once it's correctly entered.  In any case...)

Why do you want to avoid doubling the valid_pwd test?  The code size
shouldn't be a big factor, and the number of executions stays the
same.  I would think a natural control flow would be

	if (valid_pwd()) {
		validate_password();
	} else
		do {
			get_new_password();
		} while (!valid_pwd());

[I've made some things real C functions just for consistency with the
control-structure syntax.]