#include <iostream>
usingnamespace std;
int rand_function(int param)
{
if ((param / 2) == 0)
return param;
elsereturn 0;
}
int main()
{
int number = 0;
while (number == 0)
{
number = rand_function(2);
//number now equals 2
number = rand_function(45);
//number equals 0 again and the loop will continue
}
}
now my question is... is there any way to break out of this loop immediately after number changes without putting an if/break statement between every instance of the function? Or will I have to insert if/break statements every time?
is there any way to break out of this loop immediately after number changes without putting an if/break statement between every instance of the function?
I have to admit to being a bit confused by your question.
You want to break out of your loop when the variable number changes value? Or what?
Andy, what I'm asking is: is there any way I can IMMEDIATELY break out of the loop after the variable number is no longer 0. What I want to be able to do is something to the effect of
1 2 3 4 5 6 7 8 9 10
while(number == 0)
{
//some code
//some more code
//call a function that either changes the variable or keeps it at zero <--- break right
// here if not a 0
//some more code
//another type of function that does the same as the previous function
//some more code
}
Is there any way I can break out of the loop without having to use an if/break statement after every function call? So if the first function changes the variable to 1, is there any way to break out of the loop right then and there?
Is there any way I can break out of the loop without having to use an if/break statement after every function call?
The answer is pretty much no.
If you want to exit immediately you will either have to use if()s and breaks (preferred) or nested if()s.
I don't think this is an improvement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int number = 0;
while (number == 0)
{
number = rand_function(2);
if(number == 0)
{
number = rand_function(45);
if(number == 0)
{
number = rand_function(60);
// etc
}
}
}
over this
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int number = 0;
while (number == 0)
{
number = rand_function(2);
if(number != 0)
break
number = rand_function(45);
if(number != 0)
break
number = rand_function(60);
if(number != 0)
break
// etc
}
(I suppose there just might be a way to use a compound logic expression, by exploiting short circuit evauation, but it would not (!) be nice code. But haven't really thought about this.)
Andy
PS Actually, you could use exception handling instead. But that would (a) be more code, (b) go against the intended use of exceptions (which is to handle error conditions, which this is not.)