
@c This is part of The GNU C Reference Manual
@c Copyright (C) 2008-2009 Free Software Foundation, Inc.
@c See the file gnu-c-manual.texi for copying conditions.

@c ----------------------------------------------------------------------------

@node Functions
@chapter Functions
@cindex functions

You can write functions to separate parts of your program into distinct
subprocedures.  To write a function, you must at least create a function
definition.  It is a good idea also to have an explicit function
declaration; you don't have to, but if you leave it out, then the
default implicit declaration might not match the function itself, and
you will get some compile-time warnings.

Every program requires at least one function, called @code{main}.
That is where the program's execution begins.

@menu
* Function Declarations::
* Function Definitions::
* Calling Functions::
* Function Parameters::
* Variable Length Parameter Lists::
* Calling Functions Through Function Pointers::
* The main Function::
* Recursive Functions::
* Static Functions::
* Nested Functions::
@end menu

@c ----------------------------------------------------------------------------

@node Function Declarations
@section Function Declarations
@cindex function declarations
@cindex declarations, function

You write a function declaration to specify the name of a function, a
list of parameters, and the function's return type.  A function declaration
ends with a semicolon.  Here is the general form:

@example
@group
@var{return-type} @var{function-name} (@var{parameter-list});
@end group
@end example

@var{return-type} indicates the data type of the value returned by the function.
You can declare a function that doesn't return anything by using the return
type @code{void}.

@var{function-name} can be any valid identifier (@pxref{Identifiers}).

@var{parameter-list} consists of zero or more parameters, separated by commas.
A typical parameter consists of a data type and an optional name for the
parameter.  You can also declare a function that has a variable number of
parameters (@pxref{Variable Length Parameter Lists}), or no parameters using
@code{void}.  Leaving out @var{parameter-list} entirely also indicates
no parameters, but it is better to specify it explicitly with @code{void}.

Here is an example of a function declaration with two parameters:

@example
@group
int foo (int, double);
@end group
@end example

If you include a name for a parameter, the name immediately follows the
data type, like this:

@example
@group
int foo (int x, double y);
@end group
@end example

The parameter names can be any identifier (@pxref{Identifiers}), and if you
have more than one parameter, you can't use the same name more than
once within a single declaration.  The parameter names in the
declaration need not match the names in the definition.

You should write the function declaration above the first use of
the function.  You can put it in a header file and use the @code{#include}
directive to include that function declaration in any source code files that
use the function.

@c ----------------------------------------------------------------------------

@node Function Definitions
@section Function Definitions
@cindex function definitions
@cindex definitions, function

You write a function definition to specify what a function
actually does.  A function definition consists of information regarding
the function's name, return type, and types and names of parameters, along
with the body of the function.  The function body is a series of statements
enclosed in braces; in fact it is simply a block (@pxref{Blocks}).

Here is the general form of a function definition:

@example
@group
@var{return-type}
@var{function-name} (@var{parameter-list})
@{
  @var{function-body}
@}
@end group
@end example

@var{return-type} and @var{function-name} are the same as what you use
in the function declaration (@pxref{Function Declarations}).

@var{parameter-list} is the same as the parameter list used in the function
declaration (@pxref{Function Declarations}), except you
@emph{must} include names for the parameters in a function definition.

Here is an simple example of a function definition---it takes two integers as
its parameters and returns the sum of them as its return value:

@example
@group
int
add_values (int x, int y)
@{
  return x + y;
@}
@end group
@end example

For compatibility with the original design of C, you can also specify
the type of the function parameters @emph{after} the closing
parenthesis of the parameter list, like this:

@example
@group
int
add_values (x, y)
    int x, int y;
@{
  return x + y;
@}
@end group
@end example

@noindent
However, we strongly discourage this style of coding; it can cause
subtle problems with type casting, among other problems.

@c ----------------------------------------------------------------------------

@node Calling Functions
@section Calling Functions
@cindex calling functions
@cindex functions, calling

You can call a function by using its name and supplying any needed parameters.
Here is the general form of a function call:

@example
@var{function-name} (@var{parameters})
@end example

A function call can make up an entire statement, or it can be used as a
subexpression.  Here is an example of a standalone function call:

@example
@group
foo (5);
@end group
@end example

@noindent
In that example, the function @samp{foo} is called with the
parameter @code{5}.

Here is an example of a function call used as a subexpression:

@example
@group
a = square (5);
@end group
@end example

@noindent
Supposing that the function @samp{square} squares its parameter, the
above example assigns the value 25 to @code{a}.

If a parameter takes more than one argument, you separate parameters with commas:

@example
@group
a = quux (5, 10);
@end group
@end example 

@c ----------------------------------------------------------------------------

@node Function Parameters
@section Function Parameters
@cindex function parameters
@cindex parameters, function

Function parameters can be any expression---a literal value, a value stored in
variable, an address in memory, or a more complex expression built by
combining these.

Within the function body, the parameter is a local copy of the value passed into
the function; you cannot change the value passed in by changing the local copy.

@example
int x = 23;
foo (x);
@dots{}
/* @r{Definition for function @code{foo}.} */
int foo (int a)
@{
  a = 2 * a;
  return a;
@}
@end example

@noindent
In that example, even though the parameter @code{a} is modified in the
function @samp{foo}, the variable @code{x} that is passed to
the function does not change.  If you wish to use the function to change
the original value of @code{x}, then you would have to incorporate the
function call into an assignment statement:

@example
x = foo (x);
@end example

If the value that you pass to a function is a memory address (that is, a pointer), then you
can access (and change) the data stored at the memory address.  This
achieves an effect similar to pass-by-reference in
other languages, but is not the same: the memory address is simply a
value, just like any other value, and cannot itself be changed.  The
difference between passing a pointer and passing an integer lies in
what you can do using the value within the function.

Here is an example of calling a function with a pointer parameter:

@example
@group
void
foo (int *x)
@{
  *x = *x + 42;
@}
@dots{}
int a = 15;
foo (&a);
@end group
@end example

@noindent
The formal parameter for the function is of type pointer-to-@code{int}, and we
call the function by passing it the address of a variable of type @code{int}.  By
dereferencing the pointer within the function body, we can both see and change
the value stored in the address.  The above changes the value of
@code{a} to @samp{57}.

Even if you don't want to change the value stored in the address, passing the
address of a variable rather than the variable itself can be useful if the
variable type is large and you need to conserve memory space or limit
the performance impact of parameter copying.  For example:

@example
@group
struct foo
@{
  int x;
  float y;
  double z;
@};

void bar (const struct foo *a);
@end group
@end example

@noindent
In this case, unless you are working on a computer with very large memory
addresses, it will take less memory to pass a pointer to the structure
than to pass an instance of the structure.

One type of parameter that is always passed as a pointer is any sort
of array:

@example
@group
void foo (int a[]);
@dots{}
int x[100];
foo (x);
@end group
@end example

@noindent
In this example, calling the function @code{foo} with the parameter @code{a}
does not copy the entire array into a new local parameter within @code{foo};
rather, it passes @code{x} as a pointer to the first element in @code{x}.
Be careful, though: within the function, you cannot use @code{sizeof} to determine
the size of the array @code{x}---@code{sizeof} instead tells you the size of the
pointer @code{x}.   Indeed, the above code is equivalent to:

@example
@group
void foo (int *a);
@dots{}
int x[100];
foo (x);
@end group
@end example

@noindent Explicitly specifying the length of the array in the
parameter declaration will not help.  If you really need to pass an
array by value, you can wrap it in a @code{struct}, though doing this
will rarely be useful (passing a @code{const}-qualified pointer is
normally sufficient to indicate that the caller should not modify the
array).

@c ----------------------------------------------------------------------------

@node Variable Length Parameter Lists
@section Variable Length Parameter Lists
@cindex variable length parameter lists
@cindex parameters lists, variable length
@cindex function parameter lists, variable length

You can write a function that takes a variable number of arguments; these are
called @dfn{variadic functions}.  To do this, the function needs to have at
least one parameter of a known data type, but the remaining parameters are
optional, and can vary in both quantity and data type.

You list the initial parameters as normal, but then after that, use an
ellipsis: @samp{...}.  Here is an example function prototype:

@example
int add_multiple_values (int number, ...);
@end example

To work with the optional parameters in the function definition, you need
to use macros that are defined in the library header file
@samp{<stdarg.h>}, so you must @code{#include} that file.  For a
detailed description of these macros, see @cite{The GNU C
Library} manual's section on variadic functions.

@comment The above paragraph previously had a proper @ref tag to the
@comment GLIBC section in question, but it didn't seem to render
@comment properly, at least in HTML. Replacing with @cite for now;
@comment feel free to revisit later.

Here is an example:

@example
int
add_multiple_values (int number, ...)
@{
  int counter, total = 0;
  
  /* @r{Declare a variable of type @samp{va_list}.} */
  va_list parameters;

  /* @r{Call the @samp{va_start} function.} */
  va_start (parameters, number);

  for (counter = 0; counter < number; counter++)
    @{
      /* @r{Get the values of the optional parameters.} */
      total += va_arg (parameters, int);
    @}

  /* @r{End use of the @samp{parameters} variable.} */
  va_end (parameters);

  return total;
@}
@end example

@c Need to describe how the default promotion rules are applied to the
@c parameters passed in the ``...''.

To use optional parameters, you need to have a way to know how many
there are.  This can vary, so it can't be hard-coded, but if you
don't know how many optional parameters you have, then you could
have difficulty knowing when to stop using the @samp{va_arg} function.
In the above example, the first parameter to the @samp{add_multiple_values}
function, @samp{number}, is the number of optional parameters actually passed.
So, we might call the function like this:

@example
sum = add_multiple_values (3, 12, 34, 190);
@end example

The first parameter indicates how many optional parameters follow it.

Also, note that you don't actually need to use @samp{va_end} function.
In fact, with GCC it doesn't do anything at all.  However, you might want
to include it to maximize compatibility with other compilers.

@xref{Variadic Functions, Variadic Functions, Variadic Functions, libc, The GNU C Library Reference Manual}.

@node Calling Functions Through Function Pointers
@section Calling Functions Through Function Pointers
@cindex function pointers, calling through

You can also call a function identified by a pointer.   The
indirection operator @code{*} is optional when doing this.

@example
@group
#include <stdio.h>

void foo (int i)
@{
  printf ("foo %d!\n", i);
@}
@end group

@group
void bar (int i)
@{
  printf ("%d bar!\n", i);
@}
@end group

@group
void message (void (*func)(int), int times)
@{
  int j;
  for (j=0; j<times; ++j)
    func (j);  /* (*func) (j); would be equivalent. */
@}

void example (int want_foo) 
@{
  void (*pf)(int) = &bar; /* The & is optional. */
  if (want_foo)
    pf = foo;
  message (pf, 5);
@}
@end group
@end example 

@c ----------------------------------------------------------------------------

@node The main Function
@section The @code{main} Function
@cindex main function
@cindex function, main

Every program requires at least one function, called @samp{main}.
This is where the program begins executing.  You do not need to write a
declaration or prototype for @code{main}, but you do need to define it.

The return type for @code{main} is always @code{int}.  You do not have
to specify the return type for @code{main}, but you can.  However, you
@emph{cannot} specify that it has a return type other than @code{int}.

@c ??? The implementation is allowed to support alternative signatures. 

@cindex exit status
@cindex @code{EXIT_FAILURE}
@cindex @code{EXIT_SUCCESS}
@cindex return value of @code{main}

In general, the return value from  @code{main} indicates the program's
@dfn{exit status}.  A value of zero or EXIT_SUCCESS indicates success
and EXIT_FAILURE indicates an error.   Otherwise, the significance of
the value returned is implementation-defined.

@c ??? We don't define it here.

Reaching the @code{@}} at the end of @code{main} without a return, or
executing a @code{return} statement with no value (that is,
@code{return;}) are both equivalent.  In C89, the effect of this is
undefined, but in C99 the effect is equivalent to @code{return 0;}.

You can write your @code{main} function to have no parameters (that
is, as @code{int main (void)}, or to accept parameters from the
command line.  Here is a very simple @code{main} function with no
parameters:

@example
@group
int
main (void)
@{
  puts ("Hi there!");
  return 0;
@}
@end group
@end example

To accept command line parameters, you need to have two parameters in the
@code{main} function, @code{int argc} followed by @code{char *argv[]}.  You
can change the names of those parameters, but they must have those data
types---@code{int} and array of pointers to @code{char}.  @code{argc} is the
number of command line parameters, including the name of the program itself.
@code{argv} is an array of the parameters, as character strings.
@code{argv[0]}, the first element in the array, is the name of the program
as typed at the command line@footnote{Rarely, @code{argv[0]} can be a
null pointer (in
this case @code{argc} is 0) or @code{argv[0][0]} can be the null character.
In any case, @code{argv[argc]} is a null pointer.};
any following array elements are the parameters that followed the name
of the program.

Here is an example @code{main} function that accepts command line
parameters, and prints out what those parameters are:

@example
@group
int
main (int argc, char *argv[])
@{
  int counter;

  for (counter = 0; counter < argc; counter++)
    printf ("%s\n", argv[counter]);
  
  return 0;
@}
@end group
@end example

@c ----------------------------------------------------------------------------

@node Recursive Functions
@section Recursive Functions
@cindex recursive functions
@cindex functions, recursive

You can write a function that is recursive---a function that calls
itself.  Here is an example that computes the factorial of an integer:

@example
int
factorial (int x)
@{
  if (x < 1)
    return 1;
  else
    return (x * factorial (x - 1));
@}
@end example

Be careful that you do not write a function that is infinitely recursive.  In
the above example, once @code{x} is 1, the recursion stops.  However, in the
following example, the recursion does not stop until the program is interrupted
or runs out of memory:

@example
@group
int
watermelon (int x)
@{
  return (watermelon (x));
@}
@end group
@end example

Functions can also be indirectly recursive, of course.

@c ----------------------------------------------------------------------------

@node Static Functions
@section Static Functions
@cindex static functions
@cindex functions, static
@cindex static linkage

You can define a function to be static if you want it to be callable only
within the source file where it is defined:

@example
@group
static int
foo (int x)
@{
  return x + 42;
@}
@end group
@end example

@noindent
This is useful if you are building a reusable library of functions and need to
include some subroutines that should not be callable by the end user.

Functions which are defined in this way are said to have @dfn{static
linkage}.  Unfortunately the @code{static} keyword has multiple
meanings; @ref{Storage Class Specifiers}.

@c ----------------------------------------------------------------------------

@node Nested Functions
@section Nested Functions
@cindex nested functions
@cindex functions, nested
 
As a GNU C extension, you can define functions within other functions, a
technique known as nesting functions.
 
Here is an example of a tail-recursive factorial function, defined
using a nested function:
 
@example
@group
int
factorial (int x)
@{
  int
  factorial_helper (int a, int b)
  @{
    if (a < 1)
    @{
      return b;
    @}
    else
    @{
      return factorial_helper ((a - 1), (a * b));
    @}
  @}

 return factorial_helper (x, 1);
@}
@end group
@end example

Note that nested functions must be defined along with variable
declarations at the beginning of a function, and all other statements
follow.
