Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Variable parameters

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.

 
 
  Published under free license. Design by Interspire