Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

LAB 11

FUNCTIONS II
11.1 OBJECTIVES:

- To call a function by reference


- To understand the scope of a variable

11.2 PRE-LAB READING

11.2.1 FUNCTION CALL BY REFERENCE

When we use "pass by reference" technique, the parameter receives a reference to the actual variable
in the caller function, hence any changes to the parameter are reflected in the argument in the caller
function.

To pass a variable by reference, we simply declare the function parameters as references rather than as
normal variables:

void addOne(int &My_value) // My_value is a reference variable


{
My_value = My_value + 1;
} // My_value is destroyed here

int main()
{
int var = 5;
cout << "My variable = " << var << '\n';
addOne(var);
cout << "My variable = " << var << '\n';
return 0;
}

This produces the following output:

My variable = 5
My variable = 6

Note that the value of the argument var is changed by the function.

1
Activity 1
You just have shopped for Rs. 5000 via using debit card. You know that after making a transaction, your
account balance gets updated automatically. This was the function call which was made behind the
scene when you shopped:
Update_Balance(5000, My_balance);

Can you write the implementation of this function?? Test it for multiple transactions.

11.2.2 SCOPE OF A VARIABLE

Variable are used in C++, where we need storage for any value, which will change in program. They have
their own boundaries where they are accessible. Outside those boundaries variables are not accessible.
These boundaries are known as scope of variable. The Variables Scope can be divided into two
categories:

 Global Variables
A global variable is visible to all functions that are defined after it. They are defined outside of all
the functions, usually on top of the program.
 Local Variables
Local variables are the variables which exist only between the curly braces, in which they are
declared. Outside that they are unavailable and leads to compile time error.
o Parameter variables, which are defined inside the header of a function, are also a type
of local variables

You might also like