for – function in section
Each of the
for sections can be
filled with any type of expression,
including a function’s result. The middle section needs to be either a
conditional expression or an expression which can be converted into a
bool. The following loop, for example,
is perfectly legal and will iterate until it is broken out of.
for(10; 10; 10)
{// body}
In the next loop each section is filled with a function call. The loop will
iterate until it is broken out of, since the function returns 1.
int f()
{
return 1;
}
for(f(); f(); f())
{// body}
Notice that the first and third section of a for loop can be filled
with a function returning any type of result, even a
void:
void g()
{}
for(g(); f(); g())
{// body}
The middle section, though, cannot contain a void (the value must be convertible
into a
bool).
Example
#include <iostream>
#include <ctime>
using namespace std;
int f()
{
return 1;
}
void g()
{}
float h()
{
return 1.1f;
}
int main()
{
int i = 0;
for(10; 10; 10)
{
cout << "Loop 1 - Enter a number: ";
cin >> i;
if(i == 0)
break;
}
cout << endl;
for(f(); f(); f())
{
cout << "Loop 2 - Enter a number: ";
cin >> i;
if(i == 0)
break;
}
cout << endl;
for(g(); f(); g())
{
cout << "Loop 3 - Enter a number: ";
cin >> i;
if(i == 0)
break;
}
cout << endl;
for(h(); h(); h())
{
cout << "Loop 4 - Enter a number: ";
cin >> i;
if(i == 0)
break;
}
}
Output
Loop 1 - Enter a number: 3
Loop 1 - Enter a number: 0
Loop 2 - Enter a number: 5
Loop 2 - Enter a number: 0
Loop 3 - Enter a number: 1
Loop 3 - Enter a number: 0
Loop 4 - Enter a number: 6
Loop 4 - Enter a number: 0