Jump to content
  • Advertisement
Sign in to follow this  

Quick question about while loops..

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

When I set a condition for the while loop to do some stuff.. will it break out when the condition is met immediately or continue with the rest of the statements until the end of the loop ? I'm working on a cool Robot project, fun stuff. :)

Share this post


Link to post
Share on other sites
Advertisement
The condition is checked before the embodied statement is executed which is why if the condition is 'false' straight away, no loops are done. If you want to execute a statement and then check the condition, use a do..while().

Dave

Share this post


Link to post
Share on other sites
The condition is only checked at the beginning of each iteration.


int x = 0;

while ( x == 0 )
{
std::cout << "a";
x = 1;
std::cout << "b";
}

prints "ab".

If you want to break out of the loop before the iteration is done, you case use break.


int x = 0;

while ( x == 0 )
{
std::cout << "a";
x = 1;

if ( x != 0 ) break;

std::cout << "b";
}

Share this post


Link to post
Share on other sites
Like the others said, it isn't checked in-between. C++ really just works operation-by-operation; looping works like this: at the end of the loop (at the '}') the program jumps back to the beginning of the loop (the 'while' statement), re-evaluates the statement and does the loop again if it's still true. If it is not, it jumps right after the end of the loop (after the '}'), which makes it resume the program.
By using 'break' in a loop the computer jumps straight after the end of the loop directly, and using 'continue' makes it jump straight back to the start; a sort of shortcuts for the program.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!