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
User Defined functions
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.
C++ 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 {}
In this example, 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();
}
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
void quote() {
// Random Number from 1 to 4
int r = rand() % 4 + 1;
switch (r) {
case 1:
cout << "Be yourself; everyone else is already taken.\n";
break;
case 2:
cout << "The fool doth think he is wise, but the wise man knows himself "
"to be a fool.\n";
break;
case 3:
cout << "If you don't stand for something you will fall for anything.\n";
break;
case 4:
cout << "Love all, trust a few, do wrong to none.\n";
break;
}
}
int main() {
srand(time(0)); // Initialize random number generator.
quote();
return 0;
}
A function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.
For example, let us consider the function below:
void printNum(int num) {
cout << num;
}
Here, the int variable num is the function parameter.
We pass a value to the function parameter while calling the function.
int main() {
int n = 7;
// calling the function
// n is passed to the function as argument
printNum(n);
return 0;
}
Return Statement
In the pervious 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: A Program Which Finds out if the total Ascii value of a string is either odd or even
#include <iostream>
using namespace std;
string oddeven(string s){
int total = 0;
for (char c : s){
total += c;
}
if (total % 2 == 0){
return "Even String";
}
else{
return "Odd String";
}
}
int main(){
cout << oddeven("Oliver") << endl;
cout << oddeven("Noah") << endl;
return 0;
}
Function Prototype
C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype.
This provides the compiler with information about the function name and its parameters. That's why we can use the code to call a function before the function has been defined.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
Example:
C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);
}
In the above code, the function prototype is:
void add(int, int);
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.
C++ User-defined Function Types
For better understanding of arguments and return in functions, user-defined functions can be categorised as:
Function with no argument and no return value
Function with no argument but return value
Function with argument but no return value
Function with argument and return value
Example:
#include <iostream>
using namespace std;
//Function with no argument and no return value
void test(){
cout << "This is a test.\n";
}
//Function with argument but no return value
void println(string a){
cout << a << endl;
}
//Function with no argument but return value
string start(){
return "Initialized";
}
//Function with arguments and return value
int add(int a, int b){
return a + b;
}
int main(){
test();
println("Echo Echo");
cout << start() << endl;
cout << add(4,4) << endl;
return 0;
}
Example:
// Program to compute absolute value
// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
Example 2:
#include <iostream>
using namespace std;
// function with 2 parameters
void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
// function with double type single parameter
void display(double var) {
cout << "Double number: " << var << endl;
}
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5;
double b = 5.5;
// call function with int type parameter
display(a);
// call function with double type parameter
display(b);
// call function with 2 parameters
display(a, b);
return 0;
}
Output
Integer number: 5
Double number: 5.5
Integer number: 5 and double number: 5.5
We can understand the working of default arguments from the image in the previous slide:
When temp() is called, both the default parameters are used by the function.
When temp(6) is called, the first argument becomes 6 while the default value is used for the second parameter.
When temp(6, -2.3) is called, both the default parameters are overridden, resulting in i = 6 and f = -2.3.
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:
#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 n) {
for(int i = 1; i <= n; ++i)
{
cout << c;
}
cout << endl;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
Here is how this program works:
display() is called without passing any arguments. In this case, display() uses both the default parameters c = '*' and n = 3.
display('#') is called with only one argument. In this case, the first becomes '#'. The second default parameter n = 3 is retained.
display('#', count) is called with both arguments. In this case, default arguments are not used.
We can also define the default parameters in the function definition itself.
void display(char c = '*', int n = 3) {
for(int i = 1; i <= n; ++i) {
cout << c;
}
cout << endl;
}