Jul 4, 2011 at 2:37pm Jul 4, 2011 at 2:37pm UTC
hey,
i would like to write an "if" loop so that when the condition of the if loop is satisfied (so the statements in the if loop runs), the program quits.
i have tried exit(1); but this ends the CERN Root session in addition to ending the program. i know the use of break is not appropriate within an if loop (or so i've been told).
what would be the proper command to end the program?
Jul 4, 2011 at 3:43pm Jul 4, 2011 at 3:43pm UTC
Can you explain what you mean by an "if loop"? "if" is not a looping construct. "for", "while" and "do/while" are looping constructs in C++.
Can you show us some code? That would help us give a cogent answer to your question.
Jul 4, 2011 at 4:22pm Jul 4, 2011 at 4:22pm UTC
Loop:/goto is also a loop construct. The reserved word break is used in loops to break out of them when a condition is met.
Wazzak
Jul 4, 2011 at 4:25pm Jul 4, 2011 at 4:25pm UTC
Labels can be used to simulate loops but you cannot break out of labels...they don't wrap anything.
Jul 4, 2011 at 8:34pm Jul 4, 2011 at 8:34pm UTC
1 2 3
while (number1 == 0){
// code here
}
The downside is that the loop ends when it isn't 0, here is another solution:
1 2 3
while (number1 == 0){
return 0;
}
that way when the number equals 0, it will stop the program using return 0; You can also have it do other things inside that same loop.
Last edited on Jul 4, 2011 at 8:35pm Jul 4, 2011 at 8:35pm UTC
Jul 4, 2011 at 8:38pm Jul 4, 2011 at 8:38pm UTC
agree with logart. Personally, if I'll use return.
you can use as return 0 or just return. same effect a little different for compiler.
Jul 4, 2011 at 8:45pm Jul 4, 2011 at 8:45pm UTC
Lol we both have 31 posts :D
Jul 4, 2011 at 11:13pm Jul 4, 2011 at 11:13pm UTC
logart wrote:1 2 3
while (number1 == 0){
return 0;
}
Hmmmm once
return is encountered, the loop ends, along with the function. I don't see the point in placing a
return statement there. A simple
if statement would suffice. For example:
1 2 3 4 5 6
while ( true )
{
if ( Number == 0 )
// Break from the loop
break ;
}
Wazzak
Last edited on Jul 5, 2011 at 8:52pm Jul 5, 2011 at 8:52pm UTC
Jul 5, 2011 at 4:01pm Jul 5, 2011 at 4:01pm UTC
@Framework: one doesn't discuss goto as a looping construct in polite company. ;-)
Last edited on Jul 5, 2011 at 4:07pm Jul 5, 2011 at 4:07pm UTC
Jul 5, 2011 at 8:40pm Jul 5, 2011 at 8:40pm UTC
Mine uses only 3 lines and works just as fine?
Jul 5, 2011 at 8:55pm Jul 5, 2011 at 8:55pm UTC
logart wrote:Mine uses only 3 lines and works just as fine?
In your 2
nd loop example, your loop never lives past the first loop, therefore the loop becomes
pointless . Your 1
st example however, is fine.
Wazzak
Last edited on Jul 5, 2011 at 8:56pm Jul 5, 2011 at 8:56pm UTC
Jul 6, 2011 at 3:09am Jul 6, 2011 at 3:09am UTC
I didn't mean for them to be used in the same code, just two different solutions for the same problem, not one solution.