A function is a named unit of a group of program statements. This unit can be invoked from other parts of the program. A programmer can solve a simple problem in C++ with a single function. Difficult and complex problems can be decomposed into sub-problems, each of which can be either coded directly or further decomposed. Decomposing difficult problems, until they are directly code-able as single C++ functions, is a software engineering method of stepwise refinement. These functions are combined into other functions and are ultimately used in main() to solve the original problem.

In C++, a function must be defined before it can be used any where in the program.

where datatype specifies the type of value the function returns (e.g.: int, char, float, double, user-defined). If no datatype is mentioned, the compiler assumes it as default integer type. The parameter list is also known as the arguments or signature of the function, which are the variables that are sent to the function to work on. If the parameter list is empty, the compiler assumes that the function does not take any arguments.

Example:

The above program allows the user to input two integer values. It then lets the program compute the result by sending both the values to a function, by the name area().

A function prototype is a declaration of the function that tells the program about the type of value returned by the function and the number & type of arguments passed.

A function definition is automatically a declaration.

What are Default arguments?

C++ allows us to assign default values to function parameters, which are used in case a matching argument is not passed in the function call statement. The default values must to be specified at the time of definition.

What is pass-by-value?

A function can be invoked in two manners viz. pass-by-value and pass-by-reference . The pass-by-value method copies the actual parameters into the formal parameters, that is, the function makes its own copy of the argument and then uses them.

The main benefit of call-by-value method is that the original copy of the parameters remains intact and no alteration by the function is reflected on the original variable. All execution is done on the formal parameters; hence, it insures the safety of the data.

The drawback of call-by-value is that a separate copy of the arguments is used by the function, which occupies some memory space thus increasing the size of the program.

The figure shows that the original parameters are copied into the formal parameters in the PrintSumAve() function and then executed in the function body.