How many ways we can pass variable to a function?
Ans: There are three ways in which we can pass variables to a function:
1)By Value
void fun(int,int); //declaration
fun(a,b); //call
void fun(int x,int y) //definition
{statements;}
Explanation:
Here the values of a and b will be passed, which is assigned to x and y.
Changing the values of x and y will not affect the values of a and b.
x and y are additionally created(occupies memory) as integers.
2)By Reference
void fun(int&,int&); //declaration
fun(a,b); //call
void fun(int &x,int &y) //definition
{statements;}
Explanation:
Here the variable is itself passed and its address is captured by the function.
Changing the values of x and y will affect the values of a and b.
x and y are not created(dont occupies memory).
3)By Address
void fun(int*,int*); //declaration
fun(&a,&b); //call
void fun(int *x,int *y) //definition
{statements;}
Explanation:
Here the address of the variables are passed and it is captured by pointer of the same type.
Changing the values of *x and *y will affect the values of a and b.
x and y are additionally created(occupies memory) as integer pointers.
1. by value
ReplyDelete2. by reference
3. by pointers