Saturday, August 22, 2009


Functions can be used to structure the program by breaking it into smaller, more manageable units. The goal of using functions is again to break difficult and large problems into smaller and smaller pieces until the pieces are small and simple enough. The program is completed by combining the small pieces to work together.

In C++ a function is defined:

void Function_name ()
     The body of the function

or if the function has parameters:

void Function_name (formal_parameters)
     The body of the function

Function name is an identifier that names the function. Function name can be any name that is valid as variable name. It is sensible to choose a name that describes well what the function does. It makes the program more understandable.

The body of the function is a sequence of statements that describe the behavior of the function. Since the idea of functions is to break a large problem into more manageable parts the body shouldn't be too long. A good rule of thumb:

When the function takes more lines than fit the screen think hard how it could be divided into two or more functions that together have the same functionality.

Formal parameters is a list of declarations of the function's parameters, separated by commas. The formal parameters defined in the parameter list function like normal local variables in the function body except that they are automatically assigned the values given when the function is called with actual parameters. So formal parameters are a kind of "dummy" parameters and they are bound to actual parameters only when the function is called. A function can gain access to data and process that data through formal parameters. A function can have several parameters or none depending on the situation. The body of the function is executed by calling the function.

A function call:

The name of the function and then in parentheses expressions
  • int the same order
  • the same amount
  • of the same type

As the formal parameters define (empty parentheses if there are no parameters) and ;

When the function is called, the execution is transferred to the first executable statement in the body. When the last statement in the function has been executed, the program execution returns to the point from which the function was called.

Previous post

Next post

No comments:

Post a Comment