Home > SparkCharts > Cs > C++ > Functions

C++


 
 

Functions

Functions return at most a single value. Functions may also have a void return type, which means the function has no value returned. The values needed by the function are called parameters, and some or all of these parameters may be assigned default values. Functions may also have no parameter list.

Function format:

return_type function(type parameter=default value, type
parameter2=default value...)
{
      code
}

Functions that have not yet been declared will not be recognizable to compilers. As such, it is necessary to use a function prototype earlier in the code to describe the requirements of a function that will appear later. Function prototypes have the return type, function name, and parameter types.

Function prototype:

return_type function(type1, type2...);

To return a value, the return command is used. A function with a declared return type must return a value of the appropriate type. A function with a void return type may never return a value. The example below returns x, assuming that x is of the appropriate type.

Return statement:

return x;

Parameters are passed by either value, reference, or pointer. Parameters passed by value may be changed without affecting the original values of the passed variable. Variables passed by reference or pointer will retain any changes made to the original value when the function returns. A parameter passed by value uses the standard type identifier and is treated exactly like the base type. Parameters passed by reference have the & symbol used after the type name and are treated as the base type. Pass by pointer parameters use the * symbol after the type name and are treated as pointers of the base type.

Parameter passing example:

return type function( type PassedByValue, type &PassedByReference,
type &PassedByPointer)

It is also possible for multiple functions to have the same function name. To resolve the possible confusion, the compiler will look at the call parameters of the functions available and choose the function with the closest match, if one is available. The method of using multiple functions of the same name is called function overloading.

Function overloading example:

void function(int a) { }
void function(bool b) { }