C++ Functions
C++ Functions
In this chapter, we will learn about the C++ function and function expressions with the help of
examples.
A function is a block of code that performs a specific task.
Suppose we need to create a program to create a circle and color it. We can create two functions
to solve this problem:
a function to draw the circle
a function to color the circle
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
There are two types of function:
Standard Library Functions: Predefined in C++
User-defined Function: Created by users
In this chapter, we will focus mostly on user-defined functions.
User-defined Function
C++ allows the programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code is given a
name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined in the
body of the function.
Function Declaration
The syntax to declare a function is:
returnType functionName (parameter1, parameter2, . . .) {
// function body
}
Here's an example of a function declaration.
// function declaration void
greet() {
cout << "Hello World";
} Here,
the name of the function is greet() the
return type of the function is void
the empty parentheses mean it doesn't have any parameters
the function body is written inside {}
Note: We will learn about returnType and parameters later in this tutorial.
Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function, we
need to call it.
Here's how we can call the above greet() function.
int main() {
// calling a function
greet(); }
We then pass num1 and num2 as arguments. These values are stored by the function parameters
n1 and n2 respectively.
Figure 2 function with parameters
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.
Return Statement
In the above programs, we have used void in the function declaration. For example, void
displayNumber() {
// code
}
This means the function is not returning any value.
It's also possible to return a value from a function. For this, we need to specify the returnType of
the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example, int add (int a,
int b) { return (a +
b); }
Here, we have the data type int instead of void. This means that the function returns an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the function
is not executed.
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>
using namespace std; //
declaring a function int
add(int a, int b) {
return (a + b);
} int main()
{ int
sum;
// calling the function and storing
// the returned value in sum sum
= add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum, and then we print it.
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here, the function
is defined after the function call.
That's why we have used a function prototype in this example.
Benefits of Using User-Defined Functions
Functions make the code reusable. We can declare them once and use them multiple times.
Functions make the program easier as each small task is divided into a function.
Functions increase readability.
C++ Library Functions
Library functions are the built-in functions in C++ programming.
Programmers can use library functions by invoking the functions directly; they don't need to write
the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which these library
functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include
the header file cmath.
Example 5: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath> using
namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square root of a number. The
function declaration of sqrt() is defined in the cmath header file. That's why we need to use the
code #include <cmath> to use the sqrt() function.
The return type of all these functions is the same but that need not be the case for function
overloading.
Note: In C++, many standard library functions are overloaded. For example, the sqrt() function
can take double, float, int, etc. as parameters. This is possible because the sqrt() function is
overloaded in C++.
We can understand the working of default arguments from the image above:
1. When temp() is called, both the default parameters are used by the function.
2. When temp(6) is called, the first argument becomes 6 while the default value is used for
the second parameter.
3. When temp(6, -2.3) is called, both the default parameters are overridden, resulting in i = 6
and f = -2.3.
4. When temp(3.4) is passed, the function behaves in an undesired way because the second
argument cannot be passed without passing the first argument.
Therefore, 3.4 is passed as the first argument. Since the first argument has been defined as int, the
value that is actually passed is 3.
Example 12: Default Argument
#include <iostream> using
namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() { int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count); return
0;
}
void display(char c, int count) {
for(int i = 1; i <= count; i++)
{
cout << c;
}
cout << endl;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
Local Variable
A variable defined inside a function (defined inside function body between braces) is called a local
variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local variable exists
and can be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
Example 14: Local variable
#include <iostream> using
namespace std;
void test(); int
main()
{
// local variable to main()
int var = 5;
test();
// illegal: var1 not declared inside main()
var1 = 9;
}
void test()
{
// local variable to test()
int var1; var1 = 6;
// illegal: var not declared inside test()
cout << var; }
The variable var cannot be used inside test() and var1 cannot be used inside main() function.
Keyword auto was also used for defining local variables before as: auto int var;
But, after C++11 auto has a different meaning and should not be used for defining local variables.
Global Variable
If a variable is defined outside all functions, then it is called a global variable.
The scope of a global variable is the whole program. This means, It can be used and changed at
any part of the program after its declaration. Likewise, its life ends only when the program ends.
Example 15: Global variable
#include <iostream> using
namespace std; // Global
variable declaration int c =
12; void test(); int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test() {
++c; //
Outputs 14
cout << c;
}
Output
13
14