C++ Functions are the group of statements that can be reused. They are the building blocks of large programs. A function is a subprogram that acts on data and returns a value. The process of constructing the function (writing the statements within the function) is called “defining a function”.
The defined functions can be invoked anywhere in the program. The process of invoking the function is known as “calling the function”.
The main() function is called at the beginning of every C++ program and in turn may call additional functions. I well designed program, main () should be a short function which directs execution to other functions. Ideally, the main () function should consist primarily of function calls to the other functions.
Each function has its own name. When that name is encountered in a program, the execution of the program branches to the body of the function. When the function is finished, executions returns to the function from which it was called, and the program continue on the next line of code.
User-defined C++ functions
C++ allows programmers to define their own functions. The general form of a function definition in C++ is as follows:
Function-type function-name (parameter-list)
- If the functions returns a value then the datatype of the value returned, must be specified in function-type. This could be int, float or char. If the function does not return a value then the function-type must be void.
- The function name follows the same rules of composition as identifiers.
- The parameter-lists the formal parameter of the function together with their types.
- The-local-definitions are definitions of variables that are used in the function-implementation. These variables have no meaning outside the function.
- The-function –implementation consists of C++ executable statements that implement the effect of the function.
- For e.g., the following is a definition of a function in which the co-ordinates of a point(x,y) are supplied as the input and returns the distance of the point from the origin as the output.
Float distance (float x, float y)
// returns the distance of (x,y) from origin
Float dist; /local variable
Dist = sqrt (x * x + y * y);