C++ Notes: Function Concepts

Purpose of functions

The purpose of functions is to make the programmer's life easier.


For a function to work well as a conceptual unit it has to have a name that is clear to the human reader.


Each function should do only one thing. This should be done so that the conceptual unit can be understood easily. Sometimes it will be convenient to do two things in a function because you're working on the same data. Try to resist this temptation. Make two functions if you reasonably can.

Separate I/O and computation. Greater cohesion is almost always achieved by separating I/O and computation. If possible, put the I/O in main or in separate functions. If I/O is properly separated, the same functions which make up a program can be used either in a GUI or command-line program.


Functions should avoid side-effects such as communicating by means of global variables. Use of global variables increases coupling, which makes programs harder to debug and maintain.

Functional Decomposition - top-down programming - successive refinement

The top-down programming style is to write a short main program that calls on additional functions to accomplish it task. These functions should similarly be kept short and call more functions if necessary to get their task done. Start with the main function, and write only function stubs which do almost nothing except maybe print a message that they were called. Get this running, then expand one of the stubs, get this running, ... . This very productive style of programming is related to iterative programming and is one of the cornerstones of Extreme Programming.

Top-down programming is good for for small programming tasks. A better approach for larger programs is to divide them into objects.

Size - One page

It is a good idea to keep functions shorter than one page or one screen. This makes them easy to comprehend, If you want to make them larger, think about how you could break the processing into two or more functions (top-down programming).



The compiler must know about the return and parameter types before it can understand the call to a function. You should declare all of your function prototypes at the beginning of your program. This is one of the primary purposes of the system include files. If you've written a number of functions in many files, it is common to define your one include file which defines the prototypes.