using break keyword

is it true you can use break to end a loop? if so would putting a nested switch statement in a loop then using a break intended to break the switch also break the loop?
would putting a nested switch statement in a loop then using a break intended to break the switch also break the loop?
No. Likewise, a break in a loop that's inside another loop will only break the inner loop.
break will end any loop.

Note that, while you can nest them inside a conditional to break loops, a break inside a switch will break the switch, not the loop in which it is nested.

Example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using std::cout;
using std::cin;

int main(void)
{  
  bool test = true;  
  while (true)
  {
    if (test)
    {
      break;  // Breaks out of while,
    }         // even though it is inside a conditional.
  }  
  cout << "Broke out of loop one.\n\n";
  
  int count = 1;
  while (count <= 5)
  {
    switch (test)
    {
      case false:
        break;
      case true:
        break;  // Will break the switch, not the while.
      default:
        break;
    }
    cout << count << "\n";
    ++count;
  }
  
  cin.ignore();
  return 0;
}
Last edited on
hmm ok, it makes more sentence thanks for clearing that up.
something you can copy and paste and run:
only reason I made this sample some months back was because I thought break was breaking out of every loop, this obviously shows otherwise. break will break out of loops ( for, while, do/while, switch ) 1 level.
converted from java, but should be ok, I didn't test....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * @(#)ertdfg.java
 *
 *
 * @author 
 * @version 1.00 2009/12/13
 */

#include <iostream>
using std::cout;

    int main()
    {
        bool mybool=true;
    
        while (mybool)
        {
            while (mybool)
            {
                if (mybool)
                {
                    while (mybool)
                    {
                        cout << "3 MyBOoL ?: " << mybool;
                        if (mybool)
                            break;
                    }
		    cout << "3.50 MyBOoL ?: " << mybool;			
                }            
                cout << "2 MyBOoL ?: " << mybool;
                if (mybool)
                    break;   
            }
            cout << "1 MyBOoL ?: " << mybool;
            if (mybool)
                break;
        }
        cout << "0 MyBOoL ?: " << mybool;
    }
Last edited on
Topic archived. No new replies allowed.