Header Ads Widget

Call by value and Call by reference

Call by value and Call by reference both are the parameter passing techniques to the function.
Call by Value:-
                         In call by value parameter passing technique whenever a function is called the value of the argument ( Actual Arguments ) are passed to the respective formal Arguments.
Therefore changes is made in the values of the formal Argument inside the called function are not reflect in the actual Argument in caller function . 
Consider the following program to swapping the value of two variable x and y.
#include<stdio.h>

// function for swapping the
// values of two variable
void swap(int a, int b)
{
int tem;
tem=a;
a=b;
b=tem;
}

// Driver function
int main()
{
int x=10, y=20;
printf("Values before calling the function\n");
printf("x=%d y=%d\n",x,y);
// function calling
swap(x,y);

printf("Values after calling the function\n");
printf("x=%d y=%d\n",x,y);
return 0;
}

output:-
Values before calling the function
x=10 y=20
Values after calling the function
x=10 y=20


Call by Reference:-
                                In call by reference parameter passing technique :-
  1. Address of Actual Argument are passed to the Formal arguments which are pointers.
  2. Therefore the changes made using these pointers inside the called function causes the changes in the Actual arguments.
Consider the following example where the address of the actual argument are passed to the formal Argument a & b which are nothing but pointers.

#include<stdio.h>

// function for swapping the
// values of two variable
void swap(int *a, int *b)
{
int tem;
tem=*a;
*a=*b;
*b=tem;
}

// Driver function
int main()
{
int x=10, y=20;
printf("Values before calling the function\n");
printf("x=%d y=%d\n",x,y);
// function calling
swap(&x,&y);

printf("Values after calling the function\n");
printf("x=%d y=%d\n",x,y);
return 0;
}

Output:-
Values before calling the function
x=10 y=20
Values after calling the function
x=20 y=10






Recommended Post:-

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-






Post a Comment

0 Comments