We have seen that we can pass reference of a variable to a function in C++ programs if we want to change the variable value within the function. This can be achieved by using pointer also. But if we don’t want to change the value of the variable ? In such case we can pass the value ( call by value) to the function. But this style has some drawback. If we pass the variable by value then it would be collected in another variable – so creation of another variable. We can avoid such creation of variables by passing the variable by reference. Still there is some trouble. The variables may get modified within the function. This can be prevented by declaring them constant.
C++ program for cbse students to demonstrate use of const in reference variable
#include< iostream.h >
#include< conio.h >
void add(int const &i,int const &j)
{
int m=i+j;
cout<<endl<< "Address of 'm':"<<&m;
cout<<endl<< "Sum="<< m;
//i=10;/* such statement will show compile time error */
}
void main()
{
clrscr();
int a,b;
cout<< "Enter values for 'a' and 'b':";
cin>>a>>b;
cout<< endl<< "Address of 'a' and 'b':"<< &a<< ","<< &b;
cout<< endl<< "Values before calling the function:"<< a<<","<< b;
add(a,b);
cout<< endl<< "Values after calling the function:"<< a<< ","<< b;
getch();
}
No comments:
Post a Comment