for – missing sections
As stated before, each of the three
for
sections can be missing, with the
consequence that it simply won’t be executed. In the following loop:
for(int i = 0; i < 5;)
{
cout << i << " ";
i++;
}
the increment section is missing, and the iteration variable is increased
within the body. In the next one, the condition section is missing:
for(int i = 1; ; i++)
{
cout << i << " ";
if(!(i%10))
{
cout << "Get out of the loop?(y/n) ";
cin >> c;
if(c == 'y')
break;
}
}
The loop is exited by the break if and when the condition c == 'y' is met.
In the following loop, instead:
char j = 'a';
for(; j < 'f'; j++)
cout << j << " ";
the initialization section is missing. The loop is based upon a variable
declared and initialized outside the loop.
Any combination of the three
for sections
might be absent, combining as a consequence the effects described above.
In case all three sections are missing, the loop keeps iterating indefinitely,
until it is broken out of, for example by a
break
statement just like above, or by a
goto or a
return, or an
exit. For example:
for( ; ; )
{
cout << "Get out of the loop?(y/n) ";
cin >> c;
if(c == 'y')
break;
}
Example
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i < 5;)
{
cout << i << " ";
i++;
}
cout << endl << endl;
char c;
for(int i = 1; ; i++)
{
cout << i << " ";
if(!(i%10))
{
cout << "Get out of the loop?(y/n) ";
cin >> c;
if(c == 'y')
break;
}
}
cout << endl << endl;
char j = 'a';
for(; j < 'f'; j++)
cout << j << " ";
cout << endl << endl;
for( ; ; )
{
cout << "Get out of the loop?(y/n) ";
cin >> c;
if(c == 'y')
break;
}
}
(Possible) Output
0 1 2 3 4
1 2 3 4 5 6 7 8 9 10 Get out of the loop?(y/n) n
11 12 13 14 15 16 17 18 19 20 Get out of the loop?(y/n) n
21 22 23 24 25 26 27 28 29 30 Get out of the loop?(y/n) n
31 32 33 34 35 36 37 38 39 40 Get out of the loop?(y/n) n
41 42 43 44 45 46 47 48 49 50 Get out of the loop?(y/n) y
a b c d e
Get out of the loop?(y/n) n
Get out of the loop?(y/n) n
Get out of the loop?(y/n) n
Get out of the loop?(y/n) y