0

when I modify string or another variable inside the loop it's condition is recalculated each time? or once before the loop start

 std::string a("aa"); do { a = "aaaa"; } while(a.size<10) 
and what about for loop

1
  • 2
    the code there wouldnt that go into an infinate loop? Commented Nov 8, 2010 at 16:43

3 Answers 3

6

Every time. Basically it checks every time to see if the statement inside the conditional is true. If it is true, continue to loop, if it is false break the loop. That is why these constructs are called Conditional Loops

Sign up to request clarification or add additional context in comments.

4 Comments

+1: The compiler can choose to do funky things with fixed sized loops e.g. it may choose to optimise for(int i = 0; i < 5; i++) DoMyThing(); by unrolling it to DoMyThing(); DoMyThing(); DoMyThing(); DoMyThing(); DoMyThing();. But for all practical purposes assume every time.
That said, if I remember well, some recent compiler will "optimize" this infinite loop and make it differently - like jumping directly to the statement next the while. I'm not sure about it but I remember a discussion about compilers ignoring obvious infinite loops.
Be careful if the condition is changed from another thread. In that case you may need to declare the relevant variables volatile.
@starblue: That means you need an atomic variable. Using volatile in that manner is an old falsity. (You have a race condition, for example.)
1

imagine what would happen if condition is not recalculated. then if that was true to begin with it would never change and you will get an infinite loop.

having said that in your case the condition is always true (because string length doesn't change).

Comments

1

Do ... while loops will check the condition every time AFTER the inside of the loop has been executed.

For loops will check the condition every time BEFORE the inside of the loop has been executed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.