-3

I have met this a lot recently reading other people's scripts. A short example is below: Say we need input and store them in var A and B, the scheme is below:

int ok;
ok = false;
while(!ok){ 
//ask input for A
//ask input for B
ok = true;
}

I understand what it wants, but why is this scheme necessary? can I only have "ask input for A and B".

Hang Yang
  • 15
  • 4
  • 1
    It would seem more intuitive to make `ok` a `bool`. – François Andrieux Jul 28 '17 at 15:43
  • 1
    Perhaps there is error checking when accepting input. Check if there are any `continue` statements in the loop's body. – François Andrieux Jul 28 '17 at 15:43
  • The above code is the same as `do { ... } while(false);`, I think you forgot to include the important pieces of the code, for instance if statements. – Jonny Henly Jul 28 '17 at 15:43
  • [This answer](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) is syntactically specific to Python, but the techniques and semantics can be implemented in other languages. Your code is one style of user input validation. – Cory Kramer Jul 28 '17 at 15:44
  • 1
    Without seeing the actual "scripts" to judge why they might be doing this, this is a question so broad as to be meaningless. – underscore_d Jul 28 '17 at 15:47

2 Answers2

2

but why is this scheme necessary?

It is not necessary.

can I only have "ask input for A and B".

You sure can.

However, if user gives you input that is not useful (for example: you ask for the users age, and they type "horse"), then you might want to ask again. Allowing re-trying of input is generally a useful feature. The canonical control structure for repeating a piece of program is a loop.

Your example program however, sets ok unconditionally, so in that case there is really no use for the loop. The loop makes sense only if there is some form of validation that must be passed before the input is OK.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thanks, this is the answer I am looking for. – Hang Yang Jul 28 '17 at 15:48
  • there are validations in the loop body for the input. I thought it would be there even I don't use loop to allow re-trying feature. Now I learned how important to keep this loop. – Hang Yang Jul 28 '17 at 16:00
1

When there are no checks in the code you omitted, but you see this same construct all over the place, then it's a copy&paste artifact.

Someone had a piece of code that was reading input and validating it, then copied the code somewhere else, removed the validation bits, and left the rest as-is. Then they copy&pasted that code all over the place.

In my experience, this happens very often.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • nah, I am a newbie for programming, the code I was reviewing that I believe is elegant masterpiece otherwise I would not take it seriously and ask this kind of question....Thanks for your advice. – Hang Yang Jul 28 '17 at 15:57