
Explain call by value and call by reference with easy examples.

Call by value: In call by value method, the called function creates a new set of variables and copies the values of arguments into them. Example: Program showing Call by value method
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf("Swapped values are a = %d and b = %d", x, y);
}
void main()
{
int a = 7, b = 4;
swap(a, b);
printf("Original values are a = %d and b = %d", a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}
Output: Original Values are a = 7 and b = 4 Swapped values are a = 4 and b = 7
The values after swap are a = 7 and b = 4 This happens because when function swap() is invoked, the values of a and b gets copied on to x and y. The function actually swaps x and y while the original variables a and b remains intact.
Call by reference: In call by reference method, instead of passing a value to the function being called a reference/pointer to the original variable is passed. Example: Program showing Call by reference method
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("Swapped values are a = %d and b = %d", *x, *y);
}
void main()
{
int a = 7, b = 4;
swap(&a, &b);
printf("Original values are a = %d and b = %d",a,b);
printf("The values after swap are a = %d and b = %d",a,b);
}
Output: Original Values are a = 7 and b = 4 Swapped values are a = 4 and b = 7
The values after swap are a = 4 and b = 7 This happens because when function swap() is invoked, it creates a reference for the first incoming integer a in x and the second incoming integer b in y.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.