Splitting main function code into separate functions

I am fairly new to the C++ language, and I would like to know how beneficial consolidating the code help within the int main() function into separate functions would be for efficiency and clarity.

I want to know if a program can contain too many functions, what makes a snippet of code a good candidate for such a move, and generally if there is a C++ convention linked to this.

Any and all help is greatly appreciated.
Last edited on
I suppose it is possible to have too many functions -- although that could really only happen if your functions are poorly designed.

Functions have two main purposes:

1) They increase code reusability (different parts of the program can call the same function)
2) They split large jobs into smaller, more managable tasks.


When you cram your entire program into main(), it becomes much harder to follow the logic. You will often even find that your code will already be broken into logical steps.

For example, in a tic-tac-toe game, logical steps would be:

- get input from the player
- draw the board
- determine the computer's move
- see if anyone won

Those steps would all make good functions.

It also makes the overall logic flow much easier to follow. Something like this is a lot easier to understand than a main() that is 300 lines long:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
while(keepplaying)
{
  DrawBoard(gameboard);
  GetPlayerMove(gameboard);
  
  if( IsGameOver(gameboard) )
    keepplaying = false;

  DrawBoard(gameboard);
  GetComputerMove(gameboard);

  if( IsGameOver(gameboard) )
    keepplaying = false;
}
Thankyou very much!
Topic archived. No new replies allowed.