Todays topic in our C++ tutorial is Comparision between Reference variable and pointer in C++ programs.
.
Now we will see the advantage of referencing in C++ programs. Both pointer and reference variable have the same effect while they deals with a variable. But reference variable works in more elegant style. Referencing provides a clean, elegant and efficient way to pass arguments to functions that intend to change their values.
In this C++ program, we will create two structure type variables to store three types of values ( name, age and salary ) in each of them. Then we will change the values using two functions – for one variable 1st function will take address of the variable and other function will take reference of the second variable.
#include< iostream.h >
#include< conio.h >
#include< string.h >
struct tag
{
char name[30];
int age;
};
typedef struct tag EMP;
void fun1(EMP *emp1)
{
strcpy(emp1->name,"Shatavisha");
emp1->age=7;
}
void fun2(EMP &emp2)
{
strcpy(emp2.name,"Sarbani");
emp2.age=36;
}
void main()
{
clrscr();
EMP emp1={"Dhananjoy",42};
EMP emp2={"Sudhyashil",1};
fun1(&emp1);
cout<< endl<< emp1.name<< ","<< emp1.age;
fun2(emp2);
cout<< endl<< emp2.name<<","<< emp2.age;
getch();
}
No comments:
Post a Comment