Thursday, July 14, 2011

Functions: Difference Between pass by value and pass by reference with example

 DIFFERENCE BETWEEN PASS BY VALUE AND PASS BY REFERENCE WITH EXAMPLE

Difference Between pass by value and pass by reference with example

Pass by value
Pass by reference
While calling by value, variable value is passed and its value is received by the arguments in the function
While calling by reference, variable's address is passed and the pointers as arguments in the function pointes to that variable's address.
Example:
#include<stdio.h>
#include<conio.h>

void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
main()
{
int x=5, y=10;
swap(x, y); //pass by value

printf("x=%d \n y=%d", x, y);

getch();
}

OUTPUT:
x=5
y=10
Example:
#include<stdio.h>
#include<conio.h>

void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
main()
{
int x=5, y=10;
swap(&x, &y); //pass by reference

printf("x=%d \n y=%d", x, y);

getch();
}

OUTPUT:
x=10
y=5
In above example, from main() function value of x and y is sent to swap() function. The value swapped between x and y is within swap function only. So, when return back to main() function the value of x and y remains same. That is why value of x is displayed as 5 and y as 10.
Its like Ram and Laxman searing different room in Ram And Laxman story.
Here, from main() function x and y address (reference) is sent to swap() function. The value swapped between x and y is the value swapped for swap() and main() function because both's x and y points to same block of address. So, when return back to main() function the value of x and y is changed. That is why value of x is displayed as 10 and y as 5.
Its like Ram and Laxman searing same room in Ram And Laxman story.

0 comments:

Post a Comment