Write a C Program to return more than one value from a function using Call By Reference. Here’s a Simple Program to return more than one value from a function using Call By Reference in C Programming Language.
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main().
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function.
In this program, we pass the variables or arguments to the function and uses pointer to calculate Sum, Difference and Multiplication of variables and return multiple values after function call.
Below is the source code for C Program to return more than one value from a function using Call By Reference which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* Program to show how to return more than one value from a function using call by reference*/
#include<stdio.h>
func(int x, int y, int *ps, int *pd, int *pp);
int main( )
{
int a, b, sum, diff, prod;
a = 6;
b = 4;
func( a, b, &sum, &diff, &prod );
printf("Sum = %d, Difference = %d, Product = %d\n", sum, diff, prod );
return 0;
}
func(int x, int y, int *ps, int *pd, int *pp)
{
*ps = x+y;
*pd = x-y;
*pp = x*y;
}
Call by Reference
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main().
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function.
In this program, we pass the variables or arguments to the function and uses pointer to calculate Sum, Difference and Multiplication of variables and return multiple values after function call.
Below is the source code for C Program to return more than one value from a function using Call By Reference which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
OUTPUT : :
need an explanation for this answer? contact us directly to get an explanation for this answer