Explore
Placement Prep

Edit

Edit

# Difference between pass by value and pass by reference

Published on 06 Mar 2020

Passing arrays to a function:

1)int n;

2) int a[10];

• The name 'n' refers to the value stored in 'n'. So, if 'n' is passed as an argument to a function, it means passing the argument by value. Hence passing an ordinary variable refers to passing the argument by value.
• The name 'a' refers to starting address of the array. So, if 'a' is passed as an argument to a function it means passing the argument by address or reference.

## Difference between pass by value and pass by reference.

Pass by value: In pass by value, changes made to the arguments in the called function will not be reflected in the calling function.

Example:

void modify(int a);
int main()
{
int a=10;
modify(a);
printf("%d",a);    //output:10
getch();
return 0;
}

void modify(int a)
{
a=a+10;
printf("%d", a);   //output: 20
}


a is an ordinary integer variable. So, when a is passed, it is passed by value. In the modify() function, a's value is changed to 20. But the changed value is not returned to main(). Thus when a is printed in the main(), output is 10, the original value.

Pass by reference: In pass by reference, the changes made to the arguments in the called function will be reflected in the calling function.

Example:

void modify(int array1[]);
int main()
{
int array1[]={1,2,3};
int i;
modify(array1);
for(i=0; i<3; i++)
printf("%d", array1[i]);   //output: 11 12 13
getch();
return 0;
}

void modify(int array1[])
{
int i;
for(i=0;i<3;i++)
{
array1[i]+=10;
printf("%d", array1[i]);     //output: 11 12 13
}
}



Here, the array contents are changed to {11,12,13} in the user-defined function. But, though these values are not returned to the main(), the changes made to the array, are seen in the main(). So, when array1[] is printed in the main(), output is {11,12,13}