PDA

View Full Version : Multiple condition in while



scaramacai
6th June 2018, 10:03
I have this code:



bool state=true;
qDebug() << "Entering while...";
i=0;
while((state==true)||(i<3))
{
state=false;
qDebug() << "Value of counter: "<<i;
i++;
}
qDebug() << "End of while";

but the first condition seem not to work.
The output is:



Entering while...
Value of counter: 0
Value of counter: 1
Value of counter: 2
End of while


If I remove the second condition (i<3), I have



...
while(state==true)
...




//Output

Entering while...
Value of counter: 0
End of while

It seems that only one condition is allowed in while loop.
Is it possible?

high_flyer
6th June 2018, 10:37
I fail to see what is the problem.
The output you are getting is exactly what it should be with that code.
What is the output you expect?
OR
What do you want your while() condition to express?

Do you want both conditions to apply or any of them?
At the moment any of the conditions apply.

scaramacai
6th June 2018, 10:56
My idea (ok, it's wrong...):
while "state" is true OR i<3 -> cycle the code.

So if "state" is false OR i> or = 3 the {code} would not be executed.
I.E., when state is false while i==2,code isn't executed.
This seems as a && (state is true AND i=3)...

ado130
6th June 2018, 14:09
Yes, in the while condition have to be && and not ||. In the case of ||, the first condition state is false but the second condition is still true.

scaramacai
6th June 2018, 15:47
Thanks! :)