Node:Variable parameters, Next:, Previous:Pointers and initialization, Up:Pointers



Variable parameters

Now that you know something about pointers, we can discuss variable parameters and passing by reference in more detail. (See Parameters, to refresh your memory on this topic.)

There are two main ways to return information from a function. The most common way uses the return command. However, return can only pass one value at a time back to the calling function. The second way to return information to a function uses variable parameters. Variable parameters ("passing by reference") enable you to pass back an arbitrary number of values, as in the following example:

#include <stdio.h>

int main();
void get_values (int *, int *);

int main()
{
  int num1, num2;
  get_values (&num1, &num2);

  printf ("num1 = %d and num2 = %d\n\n", num1, num2);

  return 0;
}


void get_values (int *num_ptr1, int *num_ptr2)
{
  *num_ptr1 = 10;
  *num_ptr2 = 20;
}

The output from this program reads:

num1 = 10 and num2 = 20

Note that we do use a return command in this example -- in the main function. Remember, main must always be declared of type int and should always return an integer value. (See Style.)

When you use value parameters, the formal parameters (the parameters in the function being called) are mere copies of the actual parameters (the parameters in the function call). When you use variable parameters, on the other hand, you are passing the addresses of the variables themselves. Therefore, in the program above, it is not copies of the variables num1 and num2 that are passed to get_values, but the addresses of their actual memory locations. This information can be used to alter the variables directly, and to return the new values.