In this article, you will learn about C++ functions, their meaning, benefits, syntax, declaration, definition, calling(or invoking) and a lot more with example programs.
What is a function
A function is a block of code or a set of statements with a name. This block has a name, can accept values(or arguments) from outside and return value.
A function is reusable because it can be invoked from multiple places.
You might be thinking, why create a function or what is the use of functions?
A function has many benefits and it adds following advantages to an application.
1. Promotes reusability: If same set of statements needs to be executed in different files or at multiple places in the same file, then they can be grouped into a function and invoked from the required places, thus reusing the same code.
2. Prevents redundancy: Code grouped in a function removes duplicate or redundant code.
3. Reduces errors: If code used at multiple places is grouped and moved to a single location, the chances of error are reduced to a single location.
4. Reduces effort: With duplicate code, a change in logic needs to be done at all places while if the same code is written in a function at the same place, then the change needs to be done at only one point.
5. Enhances modularity: Instead of writing all the code at one place, breaking it into functions makes it modular.
Syntax
A function is a named block of code, which accepts optional parameters and returns a result if required. Syntax of defining a function is given below.
return_type function_name(optional_arguments) {
}
where,
- return_type is the data type of the value the function will return
- function_name is the name of the function with which it will be invoked or called.
- optional_arguments is comma separated arguments which the function expects to receive.
If the function has a return_type other than void
, then it should also include a return
statement followed by the value to return. This value should be of the same type as return_value.
Arguments are enclosed between parenthesis followed by curly braces. These curly braces include the statements of function also known as function body.
Name of a function can be any user defined name as per the following rules.
- Function name can not be a keyword or reserved word.
- It must start with a letter or an underscore.
- It must not start with a number or a special character(such as !, %, # etc).
- Name may contain numbers, underscore and no special character other than $.
- Name can not have spaces. If you need to use multiple words, separate them with an underscore.
Function definition
Below is an example function which does not accept any argument and does not return any value.
void print_message() { cout << "Learning C++ functions"; }
This function does not return any value hence its return type is void
.
Function definition with arguments
Above function simply prints a message when invoked. Let’s make it more dynamic by supplying the message to print, from outside as argument.
void print_message(string message) { cout << message; }
Function argument names can be any valid user defined name. They should declare the type of data that they will contain such as string
in this case.
Argument will be referred inside the function body with the given name.
Function with return values
Simplest example of a function that returns a value is a function which accepts two numbers and returns their sum is given below.
int add_numbers(int first, int second) { return first + second; }
Notice the return
statement at the end. return
must be the last statement in a function.
Calling a function
A function can be called or invoked by using its name followed by parenthesis and argument values if any. If the function returns a value, then a variable should be written at the left side of function call as shown in example below.
#include <iostream> using namespace std; //no argument, no return value void print() { cout << "Learning C++ functions\n"; } // single argument, no return value void print_message(string m) { cout << m; } // two arguments with return value int add(int first, int second) { return first + second; } int main() { // invoke function print(); // invoke function with argument print_message("Calling function with argument\n"); // invoke function and store its return value int sum = add(5, 10); cout << "Sum of numbers is " << sum; return 0; }
Note that call statement only includes argument names(if they are variables) or values, it does not include the type of arguments.
When the program is executed, it prints the below output.
Learning C++ functions
Calling function with argument
Sum of numbers is 15
Values supplied as arguments to the function while calling can be variables or direct values.
Function arguments
Arguments written in function definition are known as formal arguments. Thus, in the below definition, first and second are formal arguments.
int add(int first, int second){}
Arguments supplied when calling a function are called actual arguments. In the below example, numOne and numTwo are actual arguments.
int main() { int numOne = 2; int numTwo = 15; add(numOne, numTwo); // more code }
Function prototype
If you are defining a function after main
method, then you also need to provide prototype of that function.
Function prototype is a template of function which declares the skeleton or header of the function. It includes return type, name and argument list of function.
Function template or prototype does not contain any statements and ends with a semi-colon instead of curly braces.
It is just an information to the compiler that the program will be using this function and it is defined later.
Example of function prototype is given below.
void print_message(string m);
Argument names in the template and function definition may differ. Thus, above function may be defined as
void print_message(string message) { // more code }
Name of function, its return type, count and type of arguments in function template should exactly match the function definition.
Moreover, since the argument names in function template are never used, they are just for informing the count and types of arguments to the compiler, argument names can be omitted.
Thus, above function template or prototype can be modified as
void print_message(string);
Lastly, declaring a function is only required if you are defining a function after main
method.
Default arguments
Many times the value of a function argument is fixed such as interest rate in a loan application. If it is not passed from the calling function, its value should be known to the function.
C++ functions provide the support of default arguments which are initialized in the function definition. If they are not supplied while calling the function, then their default value is used. Example,
int add(int first, int second = 20) { return first + second; }
Here, last argument is a default argument. If the calling function provides only one value, then the value of second argument will be initialized to 20.
If the calling function provides a value for default argument, then default value is ignored and supplied value is given preference. Example,
call(5); // return value will be 25 call(5, 10); // return value will be 15
A function can declare any number of default arguments.
Remember that default arguments are added from right to left. This means that function arguments starting from right can have default values.
You can not assign default values to arguments in the middle. Thus, below function definition is invalid.
void default_example(int x, int y=10, string s) { }
This makes sense since when the function is called the missing arguments from right are considered as default.
Function call flow
When a function is called, the control shifts to the function and its statements are executed line by line.
After the function call completes, the control is returned back to the calling function and the statements written after the function call are then executed.
Function invocation flow can be understood by the following illustration.
Inline function
When a function is called, the current state of calling function is saved, arguments are pushed on the stack, called function is returned after executing.
Thus, it is an expensive task.
In order to save execution time, C++ provides the concept of inline functions. When these functions are called, their call is replaced with the body of the function thus preventing the extra processing.
Functions which are smaller(usually of one or two lines) should be made inline. An inline function is created by adding inline
keyword to function definition as shown below.
inline int add(int one, int two) { return one + two; }
Note that replacing the function call with its body is the decision of compiler, it may not do so and execute an inline function as a normal function if the function is not smaller.
Call by reference
When a function is called, a copy of arguments is passed to the function. Any changes made to the argument values will not be visible in the calling function. Example,
void swap(int x, int y) { // interchange argument values int t = x; x = y; y = t; } int main() { int a = 10, b=5; cout << "Before call: a = " << a << ", b=" << b << "\n"; swap(a, b) cout << "Before call: a = " << a << ", b=" << b << "\n"; }
Above example contains a function which accepts two arguments and exchanges their values.
Calling function prints the values of arguments before and after calling the function.
Here is the output
Before call: a = 10, b= 5
After call: a = 10, b= 5
Look, the values of variables are the same even after the called function completes. This is because functions in C++ are call by value.
This means that instead of passing values, references(or memory locations) of the arguments are passed.
For using the reference of arguments, function arguments must be preceded with &(ampersand) symbol. Example,
void swap(int &x, int &y) { // interchange argument values int t = x; x = y; y = t; } int main() { int a = 10, b=5; cout << "Before call: a = " << a << ", b=" << b << "\n"; swap(a, b) cout << "Before call: a = " << a << ", b=" << b << "\n"; }
When arguments are declared this way, operations are performed directly on the memory locations rather than copies.
Above program when executed prints
Before call: a = 10, b= 5
After call: a = 5, b= 10
Values of arguments are now exchanged.
That is all on functions in C++. Hit the clap if the article was useful.