Ending a program within an "if" loop - break, exit(1), or something else?

Jul 4, 2011 at 2:37pm
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
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
closed account (zb0S216C)
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
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
closed account (GbX36Up4)
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:38pm
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
closed account (GbX36Up4)
Lol we both have 31 posts :D
Jul 4, 2011 at 11:13pm
closed account (zb0S216C)
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 4:01pm
@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 8:40pm
closed account (GbX36Up4)
Mine uses only 3 lines and works just as fine?
Jul 5, 2011 at 8:55pm
closed account (zb0S216C)
logart wrote:
Mine uses only 3 lines and works just as fine?

In your 2nd loop example, your loop never lives past the first loop, therefore the loop becomes pointless. Your 1st example however, is fine.

Wazzak
Last edited on Jul 5, 2011 at 8:56pm
Jul 6, 2011 at 3:09am
closed account (GbX36Up4)
I didn't mean for them to be used in the same code, just two different solutions for the same problem, not one solution.
Topic archived. No new replies allowed.