Function that return multiple values


So far, we have specific functions that give only one value using the return statement. This is because a return statement can only give one value. Suppose, however, that we want to get more information from a function. We can achieve this in C by using arguments not only to retrieve data but also to return data to the calling function. The arguments used to "send out" data are called output parameters.

Known as the address operator (&) and indirection operator (*) which are used to achieve the process of returning data through arguments. Let us consider an example to illustrate this.

Program
#include <stdio.h>
void mathOperations(int x, int y, int *mul, int *div);
int main() {
  int m,d;
  mathOperations(10, 2, &m, &d);
  printf("m = %d\n",m);
  printf("d = %d",d);
  return 0;
}
void mathOperations(int x, int y, int *mul, int *div)
{
  *mul = x * y;
  *div = x / y;
}

In the above program, m and d are output arguments. In the function call, while we pass the value in the functions, we pass the addresses of locations where the values of m and d are store in the memory. When the function is called the following assignments occur :

address of  m to mul
address of  d to div

Note that indirection operator * in the declaration of mul and div in the header indicates these variables are to store addresses, not actual values of variables. Now, the variables mul and div point to the memory locations of m and d respectively.

In the body of the function, we have two statements :

*mul = x + y;
*div = x / y;

Note :

  1. The types of the actual and formal arguments must be the same.
  2. The actual arguments must be the addresses of variables that are local to the calling function.
  3. The formal arguments in the function header must be prefixed by the indirection operator *.
  4. Arguments in the prototype must be denoted by the symbol *.
  5. To access the value of an actual argument in the said function, we must use the predefined formal argument along with the formal operation *.