When a while loop checks its state

Hi, I have something like: Version 1:

bool noErrors = true;
while(noErrors)
{
   noErrors = ValidateControl(txtName);

   // other code
}

Version 2:

bool noErrors = true;
while(noErrors)
{
   if(!ValidateControl(txtName)) break;

   // other code
}

I use this code to validate the form, and if the validation returns false, I want to break it before executing the “other code”. Since I don’t know when the loop checks its state, I don’t know which makes more sense. Should I use the first or second version, or perhaps the third?

thank you for your time

+3
source share
8 answers

Version 2 will be broken before launch //other code. Version 1 will not be checked until the next iteration begins.

bool noErrors = true;
while(noErrors) 
{    
    noErrors = ValidateControl(txtName);     
    // other code 
}

Checks before each iteration.

bool noErrors = true;
do 
{    
    noErrors = ValidateControl(txtName);     
    // other code 
} while(noErrors);

Checks after each iteration.

. , , , txtName ? - ?

while (ValidateControl(txtName)) 
{
    // other code 
} 

txtName , ,

if (ValidateControl(txtName))
{
  while(/*Some other condition*/)
  {
      // other code
  }
}
+3

. 1 " " , noErrors false ... 2 ... noErrors 2.

:

while (ValidateControl(txtName))
{
    // other code
}

?

+2

A while . .

0

( , ..). .

0

while , . do-while. №2 .

0

while . other code, 2.

0

, " " , ValidateControl false.

" ", ValidateControl false, noErrors false, . , noErrors - , while while(true), , 2:/p >

bool noErrors = true;
while(noErrors)
{
    if(!ValidateControl(txtName))
    {
        noErrors = false;
        break;
    }

    // other code
}
0

, BOTHER WHILE()... , ... , :

Function bool IsAllDataValid()
{
    if ( ! (ValidateControl(txtName) )
        return false;

    if ( ! (ValidateControl(OtherField ))
        return false;

    etc...

    return true;
}

, ... ...

if IsAllDataValid()
{
   Do Your Other Code
}
0

All Articles