The main() function is your executable program that gets compiled into machine code which can run on any machine regardless of the operating system. This is done using a linker which resolves dependencies and zip together object files with those dependencies.
The main function has to return an integer, so the operating system can determine if the program terminated successfully (i.e exits with code 0).
- In this case, this main function sets a variable difficulty (of type of integer) which has initial value of 2.
int difficulty = 2;
- Then, a variable maxDifficulty (also of type integer) is set with an initial value of 10.
int maxDifficulty = 10;
- Next, using those integer variables a while loop is used to play the game with increasing difficulty. While loop are also known as pre-test loops, where the exit condition is evaluated before iteration takes place. If the condition evaluates to true, the loop continues. The loop exits when the exit condition evaluates to false.
while (difficulty <= maxDifficulty)
{
PlayGameAtDifficulty(difficulty);
std::cin.clear(); // clears the failbit
std::cin.ignore(); // discards the buffer
++difficulty;
}
The exit condition in this loop is whether the difficulty is less than or equal to the maxDifficulty.
If true, the following statements are run
a. > PlayGameWithDifficulty(difficulty);
This is a function that accepts an integer parameter that handles the game logic. No value is returned since the function is declared as void.
b. > std::cin.clear();
This std::cin object uses the clear method to clear the fail bit.
c. > std::cin.ignore();
This std::cin object uses the ignore method to discard the buffer.
d. > ++difficulty;
This statement uses a pre-increment operator to increasing the value stored in difficulty by one. This ensures that the loop doesn’t continue infinitely.
if false the loop exits and the program continues.
-
cout << “WOW - you’re a master programmer\n”;
This line prints a congratulatory message to the screen.
-
return 0;
This value is returned to the operating system, if the programmed terminated successfully.