Bodyless for
Just like in any other loop, the body of a
for can be missing. In that case,
it is typical that any meaningful computation takes place inside one or more
of the
for sections. In the following loop,
which is an extract from the example at the end of the page:
for( ; guessNumber(); cout << endl);
there is no body and the function
guessNumber()
contains the statements which will be repeated at each iteration and
which give meaning to the loop (the function asks the user to input
a number and checks if it matches against a randomly selected one –
in which case the function returns 0 and the loop is exited).
Example
#include <iostream>
#include <ctime>
using namespace std;
int guessNumber()
{
static numberToGuess = rand()%11; //gets initialized only once.
cout << "Guess Number! ";
int number;
cin >> number;
return numberToGuess - number;
}
int main()
{
// Seed the random-number generation with current time
srand( (unsigned)time( NULL ) );
for( ; guessNumber(); cout << endl);
cout << "YOU GUESSED!";
}
(Possible) Output
Guess Number! 3
Guess Number! 7
Guess Number! 1
Guess Number! 2
Guess Number! 4
YOU GUESSED!