Monday, October 7, 2013

CBSE2009AQ1. What is the difference between call by value and call by reference? Give an example in C++ illustrate both.

 Call by value
 Call by reference
  1. A copy of value or argument passed from calling routine to the function.
  2. The original value doesn't change by called function.
  1. The original value or argument passed from calling routine to the function.
  2. The original value can change by called function.

Coding for Call by value:

#include <iostream>
using namespace std;

// function declaration
void swap(int x, int y);


int main ()
{
   // local variable declaration:
   int a = 100;
   int b = 200;

   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using value*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;

   return 0;
}

void swap(int x, int y)
{
    int temp;
    temp = x;
    x=y;
    y=temp;
    
}

Coding for Call by reference:

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);


int main ()
{
   // local variable declaration:
   int a = 100;
   int b = 200;
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using variable reference.*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
   return 0;
}

void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x=y;
    y=temp;
    
}

No comments:

Post a Comment