7.
Modular
Programming with
Functions
The process of splitting a large program into small
manageable tasks and designing them
independently is popularly called modular
programming or divide-and-conquer technique.
A repeated group of instructions in a program can
be organized as a function. It can be invoked
instead of having the same pattern of code
wherever it is required.
A function can be invoked which behaves as
though its code is inserted at the point of the
function call.
Functions can be accessed repeatedly without
redevelopment, which in turn promotes reuse of
code.
C++ makes prototyping mandatory if functions are
defined after the function main. If the function is
defined before its invocation then its prototype
declaration is optional.
C++ assumes void type in case no arguments are
specified in the argument list; the default return
type is an integer.
The function itself is referred to as function
definition. The first line of the function definition is
known as function declarator and is followed by the
function body.
In the case of a program having a large number of
functions, the programmer has to arrange the
functions such that they are defined before they
are called by any other function.
The return value can be a constant, a variable, a
user-defined data structure, a general expression
(reducible expressions), a pointer to a function or a
function call (in which case the call must return a
value).
C++ does not place any restriction on the type of
return value, except that it cannot be an array (a
pointer to an array can be returned. A function can
return an array that is a part of a structure).
Library functions are shipped along with the
compilers. They are predefined and precompiled
into library files, and their prototypes can be found
in the files with .h (called header files) as their
extension in the include directory. The definitions
are available in the form of object codes in the files
with .lib(called library files) as their extension in
the lib directory.
The parameters used to transfer data to a function
are known as input parameters and those used to
transfer the result to the caller are known as
output parameters. The parameters used to
transfer data in both the directions are called input
output parameters.
The formal parameters are those specified in the
function declaration and function definition. The
actual parameters are those specified in the
function call.
Parameters without default arguments are placed
first, and those with default values are placed later
(because of the C++ convention of storing the
arguments on the stack from right to left).