Docsity

Functions: Call by Value & Call by Reference – Complete C++ Notes, Study notes of Information Technology

Partial preview of the text

Download Functions: Call by Value & Call by Reference – Complete C++ Notes and more Study notes Information Technology in PDF only on Docsity!

Functions

Call by value & Call by reference

By Anam Javaid COMSATS University Islamabad, Wah Campus

Previous Lecture

Functions

Parameter Passing to the Function

Scope of Variables

Call by Value

  • When an argument is passed into a parameter, only a copy of the argument’s value is passed. Changes to the parameter do not affect the original argument.

Call by Reference

  • When used as parameters, reference variables allow a function to access he parameter’s original argument. Changes to the parameter are also made to the argument.
  • A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias.
  • Reference variables are defined like regular variables, except you place an ampersand (&) in front of the name. For example, the following function definition makes the parameter refVar a reference variable: void doubleNum(int &refVar) { refVar *= 2; }

Understanding Reference Variables

Reference Variables

  • Activity: What is pass-by-value? What is pass-by-reference? Show the result of the following programs:
  • • Activity
  • • Activity

Pass by Pointer

  • In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So the following questions are inevitable; when is one preferred over the other? What are the reasons we use one over the other?

Difference in Reference variable and pointer variable 1.A pointer can be re-assigned while reference cannot, and must be assigned at initialization only.

  1. Pointer can be assigned NULL directly, whereas reference cannot.
  2. Pointers can iterate over an array, we can use ++ to go to the next item that a pointer is pointing to.
  3. A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.
  4. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.

int main() { int x = 5; int y = 6; int *p; p = &x; p = &y; // 1. Pointer reintialization allowed int &r = x; // &r = y; // 1. Compile Error r = y; // 1. x value becomes 6 p = NULL; // &r = NULL; // 2. Compile Error p++; // 3. Points to next memory location r++; // 3. x values becomes 7 cout << &p << " " << &x << endl; // 4. Different address cout << &r << " " << &x << endl; // 4. Same address cout << p << endl; // 6. Prints the address cout << r << endl; // 6. Print the value of x return 0; }