Node:Function examples, Next:, Previous:Function names, Up:Functions



Function examples

Here is an example of a function that adds two integers and prints the sum with C's "print formatted" function named printf, using the characters %d to specify integer output.

void add_two_numbers (int a, int b)               /* Add a and b */
{
  int c;

  c = a + b;
  printf ("%d\n", c);
}

The variables a and b are parameters passed in from outside the function. The code defines a, b, and c to be of type int, or integer.

The function above is not much use standing alone. Here is a main function that calls the add_two_numbers function:

int main()
{
  int var1, var2;

  var1 = 1;
  var2 = 53;

  add_two_numbers (var1, var2);
  add_two_numbers (1, 2);

  exit(0);
}

When these functions are incorporated into a C program, together they print the number 54, then they print the number 3, and then they stop.