Friday 24 April 2009

Example showing Pass by Value and Pass by Reference

This is a very simple example of Pass by value and pass by reference. I have shown both the simple type and structures in the same example.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing pass by value and pass by reference

#include<iostream>

using namespace
std;

//Pass by value
void func1(int num)
{

num++;
}


//Pass by reference
void func2(int &num)
{

num++;
}


typedef struct
x
{

int
a;
int
*b;
}
X ;

//Pass by value, pointer still incremented in b
void newFunc1(X xyz)
{

xyz.a++;
(*
xyz.b)++;
}


//Pass by reference, both variables incremented
void newFunc2(X &xyz)
{

xyz.a++;
(*
xyz.b)++;
}


int
main()
{

int
someNum = 3;
cout<<"\n1. someNum = "<<someNum<<endl;
func1(someNum);
cout<<"\n2. someNum = "<<someNum<<endl;
func2(someNum);
cout<<"\n3. someNum = "<<someNum<<endl;

cout<<"\n\nTrying this on structures"<<endl;
X someX;
someX.a = 13;
int
number = 50;
someX.b = &number;
cout<<"\n1. someX.a = "<<someX.a<<" someX.b = "<<*someX.b<<endl;
newFunc1(someX);
cout<<"\n2. someX.a = "<<someX.a<<" someX.b = "<<*someX.b<<endl;
newFunc2(someX);
cout<<"\n3. someX.a = "<<someX.a<<" someX.b = "<<*someX.b<<endl;
cout<<endl;
return
0;
}




The output is as follows:

No comments:

Post a Comment