You are here


6 February, 2015 - 16:27

The break is used in one of two ways; with the switch (a C++ programming structure) to make it act like a case structure (it's more common name within most programming languages) or as part of a looping process to break out of the loop. The first usage is allowed in good structured programming and the second is not allowed in good structured programming.

Example 12.6: C++ source code

switch (age)  {  case 18: cout  << "\nYou can vote.";           break;  case 39: cout  << "\nYou are middle aged.";           break;  case 65: cout  << "\nYou are at retirement age.";           break;  default: cout  << "\nYour current age is not important.";}

The following is an unauthorized use of break in a loop and it gives the appearance that the loop will execute 8 times, but the break statement causes it to stop during the fifth iteration.

Example 12.7: C++ source code

counter = 0;while(counter  < 8)  {  cout  <<  counter << endl;  if (counter == 4)    {    break;    }  counter++;  }