|
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. #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. #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. | ||
|
|
||