You are on page 1of 2

OS LAB CALL BY ADRESS & CALL BY REFERENCE Ex. No.

– 2

mn#include "stdafx.h"

#include<iostream>

using namespace std;

void swap(int *x,int *y);

void main()

int i,j;

i=10; j=20;

cout<<"\n the value of i before swapping is:"<<i;

cout<<"\n the value of j before swapping is:"<<j;

swap (&i,&j); // call swap() with addresses of i and j

cout<<"\n the value of i after swapping is:"<<i;

cout<<"\n the value of j after swapping is:"<<j;

void swap(int *x,int*y)

int temp=*x;

*x=*y;

*y=temp;

Asst. Lect. Amthal Khaleel Page 1 of 2


OS LAB CALL BY ADRESS & CALL BY REFERENCE Ex. No. – 2

Call By Reference
To illustrate reference parameters in actual use—and to fully demonstrate their benefits—the swap( )
function is rewritten using references in the following program. Look carefully at how swap( ) is
declared and called.

#include <iostream>
using namespace std;

void swap(int &x, int &y); // Declare swap() using reference parameters.

int main()
{
int i, j;
i = 10;
j = 20;
cout << "Initial values of i and j: ";
cout << i << ' ' << j << '\n';
swap(j, i);
cout << "Swapped values of i and j: ";
cout << i << ' ' << j << '\n';
return 0;
}

/* Here, swap() is defined as using call-by-reference,


not call-by-value. Thus, it can exchange the two
arguments it is called with.
*/
void swap(int &x, int &y)
{
int temp;
temp = x; // save the value at address x
x = y; // put y into x
y = temp; // put x into y
}
Notice again that by making x and y reference parameters, there is no need to use
the * operator when exchanging values.

Asst. Lect. Amthal Khaleel Page 2 of 2

You might also like