Header Ads Widget

Ticker

6/recent/ticker-posts

Function that return multiple value

 4.6. Function that return multiple value:

Any function returns only single value at a time using return type.

If multiple values are return back to the calling function then pass arguments to a function by reference. Because in call by reference actual old values in calling function get changed that means changed values are return to calling function indirectly. So while returning multiple values use call by reference.

Program: Implement a function that returns both sum and difference values to calling function.

#include< stdio.h >

#include< conio.h >

void sumdiff (int x, int y ,int *sum ,int *diff);

void main()

{

int x=20 ,y=10 ,sum, diff;

sumdiff (x ,y ,&sum ,&diff);

printf(“sum =%d \n difference=%d \n”,s,d);

getch();

}

void sumdiff (int a, int b, int *sum, int *diff)

{

*sum = a + b;

*diff = a - b;

}

Output:

sum = 30

difference=10

Explanation:

Here, *sum=a+b; statement1

*diff=a-b; statement2

In statement1, values of a and b are added and stored in the memory location pointed to by sum pointer, this memory location is same as memory location of sum value variable in main function.

Therefore, value stored in location pointed to by sum pointer is value of sum in main function. Similarly diff pointer stores value in diff value variable in main function.

So actual sum and diff value variables in main get changed by diff and sum pointer type variables in sumdiff function.

That is by passing arguments to a function sumdiff by reference old values in main function get changes means actually sum and diff value variable is return by the sumdiff function not directly by using return type but indirectly by passing argument to a function by reference.

Post a Comment

0 Comments