Node:Parameters, Next:, Previous:Expressions and operators, Up:Top



Parameters

Ways in and out of functions.

Parameters are the main way in C to transfer, or pass, information from function to function. Consider a call to our old friend calculate_bill:

total = calculate_bill (20, 35, 28);

We are passing 20, 35, and 28 as parameters to calculate_bill so that it can add them together and return the sum.

When you pass information to a function with parameters, in some cases the information can go only one way, and the function returns only a single value (such as total in the above snippet of code). In other cases, the information in the parameters can go both ways; that is, the function called can alter the information in the parameters it is passed.

The former technique (passing information only one way) is called passing parameters by value in computer programming jargon, and the latter technique (passing information both ways) is referred to as passing parameters by reference.

For our purposes, at the moment, there are two (mutually exclusive) kinds of parameters:

Consider a slightly-expanded version of calculate_bill:

#include <stdio.h>

int main (void);
int calculate_bill (int, int, int);

int main()
{
  int bill;
  int fred = 25;
  int frank = 32;
  int franny = 27;

  bill = calculate_bill (fred, frank, franny);
  printf("The total bill comes to $%d.00.\n", bill);

  exit (0);
}

int calculate_bill (int diner1, int diner2, int diner3)
{
  int total;

  total = diner1 + diner2 + diner3;
  return total;
}

Note that all of the parameters in this example are value parameters: the information flows only one way. The values are passed to the function calculate_bill. The original values are not changed. In slightly different jargon, we are "passing the parameters by value only". We are not passing them "by reference"; they are not "variable parameters".

All parameters must have their types declared. This is true whether they are value parameters or variable parameters. In the function calculate_bill above, the value parameters diner1, diner2, and diner3 are all declared to be of type int.