C++ Functions: 1) Code Reusability
C++ Functions: 1) Code Reusability
C++ Functions: 1) Code Reusability
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header
files such as ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a
big program and optimizes the code.
Declaration of a function
The syntax of creating function in C++ language is given below:
return_type function_name(data_type parameter...)
{
//code to be executed
}
References in C++
References are like constant pointers that are automatically dereferenced. It is
a new name given to an existing storage. So when you are accessing the
reference, you are actually accessing that storage.
int main()
{ int y=10;
int &r = y; // r is a reference to int y
cout << r;
}
Output :
10
There is no need to use the * to dereference a reference variable.
int main()
{
int a = 10;// say address of 'a' is 2000;
int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
int c = *p; //*p means dereferencing. it will give the content of the address
pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable],
content of 2000 is 10. so *p will give 10.
}
Difference between Reference and Pointer
References Pointers
// Function prototype
void swap(int&, int&);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a, b);
return 0;
}
void swap(int& n1, int& n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
Output
Before swapping
a=1
b=2
After swapping
a=2
b=1
In main(), two integer variables a and b are defined. And those integers are
passed to a function swap() by reference.
Compiler can identify this is pass by reference because function definition
is void swap(int& n1, int& n2) (notice the & sign after data type).
Only the reference (address) of the variables a and b are received in
the swap() function and swapping takes place in the original address of the
variables.
In the swap() function, n1 and n2 are formal arguments which are actually same
as variables a and b respectively.
There is another way of doing this same exact task using pointers.
Example 2: Passing by reference using pointers
#include <iostream>
using namespace std;
// Function prototype
void swap(int*, int*);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
Since the address is passed instead of value, dereference operator must be used
to access the value stored in that address.
The *n1 and *n2 gives the value stored at address n1 and n2 respectively.
Since n1 contains the address of a, anything done to *n1 changes the value
of a in main() function as well. Similarly, b will have same value as *n2.