Page 80 - Modular_V1.1_Flipbook
P. 80
Call by Reference
In call by reference technique, reference or memory address of the variables are passed to a
function. In this technique, changes made to the parameters inside the function are reflected on
the arguments.
Program 4: To swap two numbers by using call by reference method of function call.
#include<iostream.h>
#include<conio.h>
void swap(int *num1, int *num2);
void main(){
int a = 10, b = 20;
clrscr();
cout<<”The values before swapping are: “<<a<<” and “<<b<<”\n”;
swap(&a, &b);
cout<<”The values of and b are: “<<a<<” and “<<b<<”\n”;
getch();
} Output:
void swap(int *num1, int *num2){ The values before swapping are:
int temp; 10 and 20
temp = *num1; The values after swapping are: 20
and 10
*num1 = *num2;
The values of and b are: 20 and 10
*num2 = temp;
cout<<”The values after swapping are: “<<*num1<<” and “<<*num2 <<”\n”;
}
In the preceding program, the references of the parameters are passed to the function by using
the address operator (&) as:
swap(&a, &b);
You need to pass the formal arguments to the function with the help of dereference operator (*) as:
swap(int *num1, int *num2)
SCOPE OF VARIABLES
The scope of a variable means how the different parts of the program can access that variable.
There are two main types of scopes for variables in C++: local and global.
Local Variables
The variables which are declared in the body of a function or block are called local variables for
that function. You can use these variables only inside the function in which they are declared. If
you try to use the local variables outside their scope, C++ compiler will show an error message.
Global Variables
The variables that are declared outside of all the functions are called global variables. Global
variables can be used by any function in the program. Generally, global variables are declared
just below the preprocessor directive.
78 Touchpad MODULAR (Version 1.1)-X

