FunctionX - Practical Learning Logo

C++ Keywords: break

The break keyword is used to stop a loop for any reason you consider fit. The break statement can be used in a while condition to stop an ongoing action. The following program tries to count alphabetical letters from d to n, but a break makes it stop when it encounters k:

#include <iostream>

using namespace std;



//---------------------------------------------------------------------------



int main(int argc, char* argv[])

{

    char Letter = 'd';



    while( Letter <= 'n' )

    {

        cout << "Letter " << Letter << endl;

        if( Letter == 'k' )

            break;

        Letter++;

    }



    return 0;

}

The break statement can be used in a do…while loop in the same way.

In a for statement, the break can stop the counting when a particular condition becomes true. For example, the following program is supposed to count from 0 to 12, but the programmer wants it to stop as soon as it detects the number 5:

#include <iostream>

using namespace std;



//---------------------------------------------------------------------------



int main(int argc, char* argv[])

{

    for(int Count = 0; Count <= 12; ++Count)

    {

        cout << "Count " << Count << endl;

        if( Count == 5 )

            break;

    }



    return 0;

}

The break statement is typically used to handle the cases in a switch statement where you usually may want the program to ignore invalid cases.

Consider a program used to request a number from 1 to 3, a better version that involves a break in each case would allow the switch to stop once the right case is found. Here is a working version of that program:

#include <iostream>

using namespace std;



//---------------------------------------------------------------------------



int main(int argc, char* argv[])

{

    int Number;



    cout << "Type a number between 1 and 3: ";

    cin >> Number;



    switch (Number)

    {

    case 1:

        cout << "\nYou typed 1.";

        break;

    case 2:

        cout << "\nYou typed 2.";

        break;

    case 3:

        cout << "\nYou typed 3.";

        break;

    default:

        cout << endl << Number << " is out of the requested range.";

    }



    return 0;

}

Copyright © 2001-2005 FunctionX, Inc.