Run if statement in loop only once

Just wondering if it's possible. Consider the following code:

boolean firstRow = true;

while{row = result.next())
{
    if(firstRow)
    {
        firstRow = false;
        //do some setup 
    }

    //do stuff
}

His pseudo-code and question is not about any particular programming language at all.

My question is: is it possible to write code that behaves in exactly the same way, but without using an additional variable (in this case "firstRow"). In the FOR loop, you can check the value of the counter variable, but it allows you to leave FOR loops from this question.

+3
source share
3 answers

Yes, do your setup before you start the loop and change it to do..while. For instance:

if (row = result.next()) {
  //do some setup 
  do {
    //do stuff
  } while (row = result.next());   
}
+4
source
if(row = result.next())
{
    //do some setup
    while(row) 
    {
        //do stuff
        row = result.next();
    }
}
0
source

, . "" . , , , , , , . , if.

if(row = result.next())
{
    //do some setup 
}
for (;row;row=result.next()) 
{
    //do stuff
}

Another would be to make your loop as simple as possible and trust your compiler optimizer to do the β€œdeploy” described above. This will probably be if you set the optimization parameters high enough.

0
source

Source: https://habr.com/ru/post/1786909/


All Articles