Local and Global Functions:
The functions that are declared inside the main function or inside any other function are called local functions. They can he called only in that function in which they are declared. The functions that are declared outside the main functions are called global functions. They can he called by any function. The function prototypes defined in the header file are treated as global functions because they can he called in any function.
Reference Parameters:
There are two ways to pass arguments to a function. These are:
- Arguments passed by value
- Arguments passed by reference
When an argument is passed by value to a function a new variable of the data type of the argument is created and the data is copied into it. The function accesses the value in the newly created variable and the data in the original variable in the calling function is not changed. The data can also he passed to a function by reference of a variable name that contains data. The reference provides the second name (or alias) for a variable name. When a variable is passed by reference to a function no new copy of the variable is created. Only the address of the variable is passed to the function. The original variable is accessed in the function with reference to its second name or alias. Both variables use the same memory location. Thus any change in the reference variable also changes the value in the original variable.
The reference parameters are indicated by an ampersand (&) sign after the data type both in the function prototype and in the function definition.
Program:
Write a program to exchange the values of two variables by using reference arguments in the function.
#include <iostream. h>
#include <conio.h>
main ( )
{
void exch (int &, int &);
int a, b;
clrscr ( );
cout << “Assign value to variable A ?” ;
cin >> a;
cout << “Assign value to variable B ?” ;
cin >>b;
exch (a, b);
cout << “Values after exchange” << endl;
cout << “Value of A = ” << a << endl;
cout << “Value of B = ” << b << endl;
cout << “Ok”;
}
void exch (int& x, int& y)
{
int t;
t = x;
x = y;
y = t;
}
In the above program, the function “exch” is declared with two int type reference parameters. The ampersand sign (&) is used with each data type. It indicates that both the parameters of the function “exch” are reference parameters. When the function “exch” is called, no ampersand sign (&) is used. The ampersand sign (&) is also used with the data type of “x” and “y” variables used in the decelerator of function definition. The “x” and “y” variables are the aliases of “a” and “b” variables, respectively. The memory location of “x” and “a” is the same and similarly, memory location of “y” and “b” is same. The structure and array variables can also be passed to the function by reference in the similar way as simple data types are passed. By default, the array variables ate passed by reference.
comment closed