|
|
|
The break and continue Statements
1. The break statement is used to exit from (i.e., break
out of) a switch statement or a loop.
// break statement in a for-loop
#include<iostream>
using namespace std;
int main()
{
for( int i=1; i<= 8; i++ )
{
if( i == 5 )
break; // exit the loop
cout << i << endl;
}
return 0;
}
% g++ break.cpp
% a.out
1
2
3
4
2. The continue statement causes the loop to immediately continue
with the next iteration (not used in switch).
// continue statement in a for-loop
#include<iostream>
using namespace std;
int main()
{
for( int i=1; i<= 8; i++ )
{
if( i == 5 )
continue; // go to next iteration
cout << i << endl;
}
return 0;
}
% g++ continue.cpp
% a.out
1
2
3
4
6
7
8
|
|