How can I stop a while loop from looping when an integer variable gets a value. By value I mean any value not just a predefined value.
int foo;
while(foo = ){
// some code
}
right when foo gets value i would like the while loop to stop.
How can I stop a while loop from looping when an integer variable gets a value. By value I mean any value not just a predefined value.
int foo;
while(foo = ){
// some code
}
right when foo gets value i would like the while loop to stop.
int foo = 0;
while (foo != value) {
// code here
}
Two ways:
while(foo != ...) {
foo = ...
}
When foo reaches the value you'd like, the loop will finish.
while(true) {
foo = ...
if(foo = ...) {
break;
}
}
This loop will always continue unless foo
reaches the value you'd like to exit on. break
will exit any loop, so in this case when foo
equals your value, it will exit.
I am interpreting "By value I mean any value not just a predefined value" as that you want the loop to break as soon as foo
gets any sort of value.
Due to the rules of local variables, any assignment to foo
must cause foo
to get a value (it being primitive, namely int).
Therefore, either no loop actually will happen and you simply assign foo
, or you'll have some conditional that when taken assigns foo
. The former is a trivial case of assigning to foo. The latter can be written as:
int foo = 0; //dummy value
while (true){
if (/*ready to assign*/){
foo = /*whatever value you assign to it*/
break;
}
}
The dummy value is used as compilers don't do very much static analysis and may complain about the value being uninitialized.