help with break

Nov 29, 2011 at 5:51pm
So i was reading a tutorial on c++ (actually the one from this site) because you never know what you will find that you didn't know before, and I came across a bit of code explaining break.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main ()
{
  int n;
  for (n=10; n>0; n--)
  {
    cout << n << ", ";
    if (n==3)
    {
      cout << "countdown aborted!";
      break;
    }
  }
  return 0;
}


with this happening:

10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!


meaning that it breaks out of the if statement and the for loop. I was under the impression that it will only break out of one control structure. Am I wrong or is this a typo?
Nov 29, 2011 at 5:53pm
break; break out of the closest loop or switch block.
Nov 29, 2011 at 6:01pm
there are many more break in the loop eg .. while , for , switch ...you can try this out .
Nov 29, 2011 at 6:13pm
@peter87: see thats my point about the closest loop wouldnt that be the if statement?
@bluecoder: do you mean that there are many ways to use break or that there are many breaks in the above code?
Nov 29, 2011 at 6:20pm
An if statement isn't a loop. By loop i mean for or while loops.
Nov 29, 2011 at 6:24pm
im sorry i read that to fast i know that if is a statement. okay now i understand so there could be ten nested if statements in a while loop and even if the break is in the most inner if it will break out of them all until is out of the while loop right?
Nov 29, 2011 at 6:25pm
yes, that's right.
Nov 29, 2011 at 6:26pm
thank you.
Topic archived. No new replies allowed.