Your browser doesn't support JavaScript Functions – Windows Programming

Functions

A function is a named, self-contained unit of code that performs a specific task, can receive data through parameters, can return a value to the code that called it, and helps to organise a program into manageable and reusable sections.

Function Prototype

The function prototype declares a function before its definition and details its name, the list of parameters the function accepts, and the return type. The compiler needs to know this information before the function is called. A function defined before main() (forward declaration) does not need a function prototype.

Function calls

A function call transfers control to a function and can supply arguments to it. The parameters in the function declaration specify the data that the function can receive. The arguments supplied in the function call provide the actual values or expressions for those parameters.

Function Parameters

The purpose of parameters is to allow functions to receive arguments. These parameters don’t have to be of the same data type. Any valid C++ data type can be a function parameter, including constants, logical expressions, objects, and other functions that return a value. Data can be passed to functions by value or by reference, and a function can have multiple parameters separated by commas.

Pass by Value – The data associated with the actual parameter is copied into a separate storage location assigned to the function parameter. Any modifications to the function parameter variable inside the called function or method affect only the local parameter.  The parameters passed to a function become local variables within that function, even if they have the same name as variables within the scope of the statement calling the function.

Pass by Reference – Using pass by reference, the function parameter becomes a reference to the original variable supplied as the argument. Changes made through the reference therefore affect the original variable.

Passing large objects by reference can be more efficient than passing them by value because it avoids copying the object. For small types such as int, the performance difference may be negligible.

The code selection below outlines 3 different methods for passing data to a function

#include <iostream> 
using namespace std;
void swapThemByVal(int, int);
void swapThemByRef(int& , int&);
void swapThemByPtr(int *, int *) ;
int main() 
{
int x = 10, y = 20;//declare and initialise variable values
swapThemByVal(x, y); // pass by value
cout << x<< "  " << y << endl;     // displays 10  20
swapThemByRef(x, y);//pass by reference
cout << x << "  " << y << endl;     // displays 20  10
swapThemByPtr(&x, &y);//pass by pointer
cout << x << "  " << y << endl;     // displays 10 20
return 0; 
}
void swapThemByVal(int num1, int num2) 
{
int temp = num1;
num1 = num2;
num2 = temp;
}
void swapThemByRef(int &num1, int &num2) 
{
int temp = num1;
num1 = num2;
num2 = temp;
}
void swapThemByPtr(int *num1, int *num2) 
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}

Default Function Parameters

Normally when a function is declared in a prototype to receive one or more parameters, the function can only be called with parameters of that data type, however, if the function prototype declares a default value for a parameter the function can be called without that parameter.

long setvalues(int x, int y, int z = 1, int t) – note that x & y are before z

The correct declaration would be

long setvalues(int x, int y, int t,int z = 1);

Passing an Array of Values to a Function

A built-in C++ array cannot be passed to a function by value as an entire array. When an array is supplied as an argument, the function receives the address of its first element. Any changes in the function will therefore be reflected in the original array. Consequently, the following parameter declarations are functionally equivalent:

C++ does not allow an entire array to be passed as an argument to a function. Pointers to an array are passed as an argument by specifying the array’s name without an index. The argument represents the memory address of the first element of the array. Any changes in the function will therefore be reflected in the original array. To pass a single-dimension array as an argument in a function using one of the following.

All these variants are functionally identical. Each effectively tells the compiler that an integer pointer is to be received.

void myFunction(int *param) - array passed as pointer void myFunction(int param[10])  - array passed a sized array void myFunction(int param[]) - array passed as unsized array

Returning Values from Functions

A function can return a value or return no value by using the void return type. To return a value, the return keyword is followed by an expression whose value is returned to the calling code. The returned value can be assigned to a variable, used in an expression, passed as an argument to another function, or ignored. A function can have multiple return statements.

Auto-Typed Return Values

Another feature added with version C++14 is the automatic deduction of a function’s return type with the auto keyword. This tells the compiler to deduce the return type of the functions by deduction –

auto subtract(int x, int y) { return x — y; }

Functions that rely on automatic return type deduction need to be defined before invoked so the compiler knows a function’s return type where it is used. If a function has multiple return statements, they need to be the same type.

Using Variables with Functions

Local Variables – A variable created in a function is called a local variable because it only exists within the function scope. Ordinary local variables have automatic storage duration. They exist while execution is within their scope and are destroyed when that scope is exited. Local variables are declared like any other variable. The parameters received by the function are also considered local variables. Local variables with automatic storage duration are commonly stored on the stack, although their actual storage is an implementation detail of the compiler.

Global Variables – In C++, variables defined outside all functions, including the main() function, are known as global variables. They can be accessed from different parts of the program, subject to their scope and linkage.

Because a global variable can potentially be accessed and changed by many different parts of a program, using global variables can make it more difficult to track down errors. Limiting the scope of a variable to the part of the program where it is needed reduces the amount of code that needs to be checked when investigating an error. For this reason, the unnecessary use of global variables is generally not considered good programming practice.

The way global variables are stored in memory is implementation-dependent. Non-constant global variables are commonly stored in a data segment or a similar area of memory.

Overloading Functions

Functions with the same name but different parameter lists are called overloaded functions. The return type is not used to distinguish overloaded functions. Overloaded functions can be used in situations where the function called depends on the type of parameters specified in the function call. It is, therefore, possible to create a function that performs a task on different data types without creating unique names for each function. For example – 

int proc(int); int proc(int, int); int proc(long, long);

The proc function above is overloaded with 3 different parameter lists. The 1st and 2nd differ in the number of parameters and the 2nd and 3rd differ in the type of parameter. The parameters the function is called with determine which function will be called. Overloaded functions don’t have to have the same return type, but it is not possible to overload by return type.  Function overloading is also called function polymorphism.

Inline Functions

The inline keyword allows a function to be defined in multiple translation units, provided the definitions are identical. It may also allow the compiler to consider the function for inline expansion, but the compiler is not required to replace a function call with the function body. Small functions are often good candidates for inline expansion

The syntax for defining the function inline is:

inline return-type function-name(parameters) { // code }

Recursion—Functions That Invoke Themselves

A function that calls itself is known as a recursive function. The recursion proceeds until some condition is met which breaks the recursive cycle. The following simple recursive function demonstrates how a countdown procedure calls itself until the exit condition is met.

#include <iostream>
void printFun(int countp) 
{ 
if (countp < 1) //exit function if value of countp is smaller than 1
return; 
else
{ 
printf("Count value = %i\n", countp);
printFun(countp-1); //recursive function calls itself
return; 
} 
} 
int main() 
{ 
int count = 3; 
printFun(count); //call recursive function
}