Passing Object To Function
There
are two ways to pass value or data to function in C language, call by value and
call by reference. Original value is not modified in call by value but it is
modified in call by reference.
1. Call by value
2. Call by reference
1. Call
by value
In call by value, value being passed to the function is
locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function
only. It will not change the value of variable inside the caller method such as
main().
Program:
1. Call
by value
In call by value, value being passed to the function is
locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function
only. It will not change the value of variable inside the caller method such as
main().
Program:
#include<iostream.h>
#include<conio.h>
void addone(int x);
void main()
{
int i;
cout<<”input one number”;
cin>>i;
addone(i);
getch();
}
void addone(int x)
{
x=x+1;
cout<<x;
}
Output:
Input one number 90
91
2.call by reference
In
call by reference, original value is modified because we pass reference
(address). Address of the value is passed in the function, so actual and formal
arguments share the same address space.Value changed inside the function, is
reflected inside as well as outside the function.
Program:
#include<iostream.h>
#include<conio.h>
void addone(int &x);
void main()
{
int i;
cout<<”input one number”;
cin>>i;
addone(i);
getch();
}
void addone(int &x)
{
x=x+1;
cout<<x;
}
Output:
Input one number 89
90
No comments:
Post a Comment