Using Boolean in loops

Jan 15, 2014 at 1:50am
Hello, I just wanted to ask on how should I go about using Boolean in loops like something along the lines of:
1
2
3
4
5
6
7
  while (true)
       {
         .
         .
         . 
         .
       }

What will this accomplish? What will while(true) satisfy?
Any simple program examples would be greatly appreciated. Thank you!
Jan 15, 2014 at 2:03am
closed account (NyqLy60M)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool running = true;
int x = 1;

while(running)
{
        std::cout << "This is message " << x << "." << std::endl;
        std::cout << "Press enter to continue..." << std::endl;
        std::cin.ignore();

        if(x >= 10)
                running = false;
        else
                x++;
}


while(true){} is essentially an infinite loop that allows you to explicitly break out under multiple circumstances you define.
Last edited on Jan 15, 2014 at 2:06am
Jan 15, 2014 at 8:12am
In the most games there is a central while() loop which goes on all the time until the user cancelles.
So, the while condition has always to be true. Different developers use different expressions; there are

1
2
3
4
5
while(1) 
while(true)
while(1==1)
for (;;)
for(;true;)
Last edited on Jan 16, 2014 at 9:09am
Jan 15, 2014 at 9:17am
while (0) is equivalent to while (false) which would make the loop pointless.
Jan 16, 2014 at 8:39am
Oh, thank you. Are there any other techniques to cancel out the bool other than what Vemc showed in his post?
Last edited on Jan 16, 2014 at 8:39am
Jan 16, 2014 at 8:49am
closed account (j3Rz8vqX)
1
2
3
4
return;
exit(1);
break;
continue;

http://mathbits.com/MathBits/CompSci/looping/end.htm

Usually break will suffice.
Jan 16, 2014 at 9:07am
In the sample that Vemc gave the bool var wasnt really necessary.
He also could have done it like that:

1
2
3
4
5
for(int i=0; i<10; i++){
std::cout << "Message number " << i << endl;
std::cout << "Press enter to continue" << endl;
std::cin.ignore();
}


This for loop does exactly the same and its easier. ;)
Jan 16, 2014 at 9:37am
jetkeynature wrote:
This for loop does exactly the same and its easier. ;)

Maybe so, but it's not what the OP asked for.
Topic archived. No new replies allowed.