This is libc.info, produced by makeinfo version 4.0b from libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.10, last updated 2001-07-06, of `The GNU C Library
Reference Manual', for Version 2.2.x.

   Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001 Free
Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU Lesser General Public License", the
Front-Cover texts being (a) (see below), and with the Back-Cover Texts
being (b) (see below).  A copy of the license is included in the section
entitled "GNU Free Documentation License".

   (a) The FSF's Front-Cover Text is:

   A GNU Manual

   (b) The FSF's Back-Cover Text is:

   You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.


File: libc.info,  Node: Threads and Fork,  Next: Streams and Fork,  Prev: Threads and Signal Handling,  Up: POSIX Threads

Threads and Fork
================

   It's not intuitively obvious what should happen when a
multi-threaded POSIX process calls `fork'. Not only are the semantics
tricky, but you may need to write code that does the right thing at
fork time even if that code doesn't use the `fork' function. Moreover,
you need to be aware of interaction between `fork' and some library
features like `pthread_once' and stdio streams.

   When `fork' is called by one of the threads of a process, it creates
a new process which is copy of the  calling process. Effectively, in
addition to copying certain system objects, the function takes a
snapshot of the memory areas of the parent process, and creates
identical areas in the child.  To make matters more complicated, with
threads it's possible for two or more threads to concurrently call fork
to create two or more child processes.

   The child process has a copy of the address space of the parent, but
it does not inherit any of its threads. Execution of the child process
is carried out by a new thread which returns from `fork' function with
a return value of zero; it is the only thread in the child process.
Because threads are not inherited across fork, issues arise. At the
time of the call to `fork', threads in the parent process other than
the one calling `fork' may have been executing critical regions of
code.  As a result, the child process may get a copy of objects that
are not in a well-defined state.  This potential problem affects all
components of the program.

   Any program component which will continue being used in a child
process must correctly handle its state during `fork'. For this
purpose, the POSIX interface provides the special function
`pthread_atfork' for installing pointers to handler functions which are
called from within `fork'.

 - Function: int pthread_atfork (void (*PREPARE)(void), void
          (*PARENT)(void), void (*CHILD)(void))
     `pthread_atfork' registers handler functions to be called just
     before and just after a new process is created with `fork'. The
     PREPARE handler will be called from the parent process, just
     before the new process is created. The PARENT handler will be
     called from the parent process, just before `fork' returns. The
     CHILD handler will be called from the child process, just before
     `fork' returns.

     `pthread_atfork' returns 0 on success and a non-zero error code on
     error.

     One or more of the three handlers PREPARE, PARENT and CHILD can be
     given as `NULL', meaning that no handler needs to be called at the
     corresponding point.

     `pthread_atfork' can be called several times to install several
     sets of handlers. At `fork' time, the PREPARE handlers are called
     in LIFO order (last added with `pthread_atfork', first called
     before `fork'), while the PARENT and CHILD handlers are called in
     FIFO order (first added, first called).

     If there is insufficient memory available to register the handlers,
     `pthread_atfork' fails and returns `ENOMEM'.  Otherwise it returns
     0.

     The functions `fork' and `pthread_atfork' must not be regarded as
     reentrant from the context of the handlers.  That is to say, if a
     `pthread_atfork' handler invoked from within `fork' calls
     `pthread_atfork' or `fork', the behavior is undefined.

     Registering a triplet of handlers is an atomic operation with
     respect to fork.  If new handlers are registered at about the same
     time as a fork occurs, either all three handlers will be called,
     or none of them will be called.

     The handlers are inherited by the child process, and there is no
     way to remove them, short of using `exec' to load a new pocess
     image.


   To understand the purpose of `pthread_atfork', recall that `fork'
duplicates the whole memory space, including mutexes in their current
locking state, but only the calling thread: other threads are not
running in the child process. Thus, if a mutex is locked by a thread
other than the thread calling `fork', that mutex will remain locked
forever in the child process, possibly blocking the execution of the
child process. Or if some shared data, such as a linked list, was in the
middle of being updated by a thread in the parent process, the child
will get a copy of the incompletely updated data which it cannot use.

   To avoid this, install handlers with `pthread_atfork' as follows:
have the PREPARE handler lock the mutexes (in locking order), and the
PARENT handler unlock the mutexes. The CHILD handler should reset the
mutexes using `pthread_mutex_init', as well as any other
synchronization objects such as condition variables.

   Locking the global mutexes before the fork ensures that all other
threads are locked out of the critical regions of code protected by
those mutexes.  Thus when `fork' takes a snapshot of the parent's
address space, that snapshot will copy valid, stable data.  Resetting
the synchronization objects in the child process will ensure they are
properly cleansed of any artifacts from the threading subsystem of the
parent process. For example, a mutex may inherit a wait queue of
threads waiting for the lock; this wait queue makes no sense in the
child process. Initializing the mutex takes care of this.


File: libc.info,  Node: Streams and Fork,  Next: Miscellaneous Thread Functions,  Prev: Threads and Fork,  Up: POSIX Threads

Streams and Fork
================

   The GNU standard I/O library has an internal mutex which guards the
internal linked list of all standard C FILE objects. This mutex is
properly taken care of during `fork' so that the child receives an
intact copy of the list.  This allows the `fopen' function, and related
stream-creating functions, to work correctly in the child process,
since these functions need to insert into the list.

   However, the individual stream locks are not completely taken care
of.  Thus unless the multithreaded application takes special
precautions in its use of `fork', the child process might not be able
to safely use the streams that it inherited from the parent.   In
general, for any given open stream in the parent that is to be used by
the child process, the application must ensure that that stream is not
in use by another thread when `fork' is called.  Otherwise an
inconsistent copy of the stream object be produced. An easy way to
ensure this is to use `flockfile' to lock the stream prior to calling
`fork' and then unlock it with `funlockfile' inside the parent process,
provided that the parent's threads properly honor these locks.  Nothing
special needs to be done in the child process, since the library
internally resets all stream locks.

   Note that the stream locks are not shared between the parent and
child.  For example, even if you ensure that, say, the stream `stdout'
is properly treated and can be safely used in the child, the stream
locks do not provide an exclusion mechanism between the parent and
child. If both processes write to `stdout', strangely interleaved
output may result regardless of the explicit use of `flockfile' or
implicit locks.

   Also note that these provisions are a GNU extension; other systems
might not provide any way for streams to be used in the child of a
multithreaded process.  POSIX requires that such a child process
confines itself to calling only asynchronous safe functions, which
excludes much of the library, including standard I/O.


File: libc.info,  Node: Miscellaneous Thread Functions,  Prev: Streams and Fork,  Up: POSIX Threads

Miscellaneous Thread Functions
==============================

 - Function: pthread_t pthread_self (VOID)
     `pthread_self' returns the thread identifier for the calling
     thread.

 - Function: int pthread_equal (pthread_t thread1, pthread_t thread2)
     `pthread_equal' determines if two thread identifiers refer to the
     same thread.

     A non-zero value is returned if THREAD1 and THREAD2 refer to the
     same thread. Otherwise, 0 is returned.

 - Function: int pthread_detach (pthread_t TH)
     `pthread_detach' puts the thread TH in the detached state. This
     guarantees that the memory resources consumed by TH will be freed
     immediately when TH terminates. However, this prevents other
     threads from synchronizing on the termination of TH using
     `pthread_join'.

     A thread can be created initially in the detached state, using the
     `detachstate' attribute to `pthread_create'. In contrast,
     `pthread_detach' applies to threads created in the joinable state,
     and which need to be put in the detached state later.

     After `pthread_detach' completes, subsequent attempts to perform
     `pthread_join' on TH will fail. If another thread is already
     joining the thread TH at the time `pthread_detach' is called,
     `pthread_detach' does nothing and leaves TH in the joinable state.

     On success, 0 is returned. On error, one of the following codes is
     returned:
    `ESRCH'
          No thread could be found corresponding to that specified by TH

    `EINVAL'
          The thread TH is already in the detached state

 - Function: void pthread_kill_other_threads_np (VOID)
     `pthread_kill_other_threads_np' is a non-portable LinuxThreads
     extension.  It causes all threads in the program to terminate
     immediately, except the calling thread which proceeds normally. It
     is intended to be called just before a thread calls one of the
     `exec' functions, e.g. `execve'.

     Termination of the other threads is not performed through
     `pthread_cancel' and completely bypasses the cancellation
     mechanism. Hence, the current settings for cancellation state and
     cancellation type are ignored, and the cleanup handlers are not
     executed in the terminated threads.

     According to POSIX 1003.1c, a successful `exec*' in one of the
     threads should automatically terminate all other threads in the
     program.  This behavior is not yet implemented in LinuxThreads.
     Calling `pthread_kill_other_threads_np' before `exec*' achieves
     much of the same behavior, except that if `exec*' ultimately
     fails, then all other threads are already killed.

 - Function: int pthread_once (pthread_once_t *once_CONTROL, void
          (*INIT_ROUTINE) (void))
     The purpose of `pthread_once' is to ensure that a piece of
     initialization code is executed at most once. The ONCE_CONTROL
     argument points to a static or extern variable statically
     initialized to `PTHREAD_ONCE_INIT'.

     The first time `pthread_once' is called with a given ONCE_CONTROL
     argument, it calls INIT_ROUTINE with no argument and changes the
     value of the ONCE_CONTROL variable to record that initialization
     has been performed. Subsequent calls to `pthread_once' with the
     same `once_control' argument do nothing.

     If a thread is cancelled while executing INIT_ROUTINE the state of
     the ONCE_CONTROL variable is reset so that a future call to
     `pthread_once' will call the routine again.

     If the process forks while one or more threads are executing
     `pthread_once' initialization routines, the states of their
     respective ONCE_CONTROL variables will appear to be reset in the
     child process so that if the child calls `pthread_once', the
     routines will be executed.

     `pthread_once' always returns 0.

 - Function: int pthread_setschedparam (pthread_t target_THREAD, int
          POLICY, const struct sched_param *PARAM)
     `pthread_setschedparam' sets the scheduling parameters for the
     thread TARGET_THREAD as indicated by POLICY and PARAM. POLICY can
     be either `SCHED_OTHER' (regular, non-realtime scheduling),
     `SCHED_RR' (realtime, round-robin) or `SCHED_FIFO' (realtime,
     first-in first-out). PARAM specifies the scheduling priority for
     the two realtime policies.  See `sched_setpolicy' for more
     information on scheduling policies.

     The realtime scheduling policies `SCHED_RR' and `SCHED_FIFO' are
     available only to processes with superuser privileges.

     On success, `pthread_setschedparam' returns 0.  On error it returns
     one of the following codes:
    `EINVAL'
          POLICY is not one of `SCHED_OTHER', `SCHED_RR', `SCHED_FIFO',
          or the priority value specified by PARAM is not valid for the
          specified policy

    `EPERM'
          Realtime scheduling was requested but the calling process
          does not have sufficient privileges.

    `ESRCH'
          The TARGET_THREAD is invalid or has already terminated

    `EFAULT'
          PARAM points outside the process memory space

 - Function: int pthread_getschedparam (pthread_t target_THREAD, int
          *POLICY, struct sched_param *PARAM)
     `pthread_getschedparam' retrieves the scheduling policy and
     scheduling parameters for the thread TARGET_THREAD and stores them
     in the locations pointed to by POLICY and PARAM, respectively.

     `pthread_getschedparam' returns 0 on success, or one of the
     following error codes on failure:
    `ESRCH'
          The TARGET_THREAD is invalid or has already terminated.

    `EFAULT'
          POLICY or PARAM point outside the process memory space.


 - Function: int pthread_setconcurrency (int LEVEL)
     `pthread_setconcurrency' is unused in LinuxThreads due to the lack
     of a mapping of user threads to kernel threads.  It exists for
     source compatibility.  It does store the value LEVEL so that it
     can be returned by a subsequent call to `pthread_getconcurrency'.
     It takes no other action however.

 - Function: int pthread_getconcurrency ()
     `pthread_getconcurrency' is unused in LinuxThreads due to the lack
     of a mapping of user threads to kernel threads.  It exists for
     source compatibility.  However, it will return the value that was
     set by the last call to `pthread_setconcurrency'.


File: libc.info,  Node: Language Features,  Next: Library Summary,  Prev: POSIX Threads,  Up: Top

C Language Facilities in the Library
************************************

   Some of the facilities implemented by the C library really should be
thought of as parts of the C language itself.  These facilities ought to
be documented in the C Language Manual, not in the library manual; but
since we don't have the language manual yet, and documentation for these
features has been written, we are publishing it here.

* Menu:

* Consistency Checking::        Using `assert' to abort if
				 something ``impossible'' happens.
* Variadic Functions::          Defining functions with varying numbers
                                 of args.
* Null Pointer Constant::       The macro `NULL'.
* Important Data Types::        Data types for object sizes.
* Data Type Measurements::      Parameters of data type representations.


File: libc.info,  Node: Consistency Checking,  Next: Variadic Functions,  Up: Language Features

Explicitly Checking Internal Consistency
========================================

   When you're writing a program, it's often a good idea to put in
checks at strategic places for "impossible" errors or violations of
basic assumptions.  These kinds of checks are helpful in debugging
problems with the interfaces between different parts of the program,
for example.

   The `assert' macro, defined in the header file `assert.h', provides
a convenient way to abort the program while printing a message about
where in the program the error was detected.

   Once you think your program is debugged, you can disable the error
checks performed by the `assert' macro by recompiling with the macro
`NDEBUG' defined.  This means you don't actually have to change the
program source code to disable these checks.

   But disabling these consistency checks is undesirable unless they
make the program significantly slower.  All else being equal, more error
checking is good no matter who is running the program.  A wise user
would rather have a program crash, visibly, than have it return nonsense
without indicating anything might be wrong.

 - Macro: void assert (int EXPRESSION)
     Verify the programmer's belief that EXPRESSION is nonzero at this
     point in the program.

     If `NDEBUG' is not defined, `assert' tests the value of
     EXPRESSION.  If it is false (zero), `assert' aborts the program
     (*note Aborting a Program::) after printing a message of the form:

          `FILE':LINENUM: FUNCTION: Assertion `EXPRESSION' failed.

     on the standard error stream `stderr' (*note Standard Streams::).
     The filename and line number are taken from the C preprocessor
     macros `__FILE__' and `__LINE__' and specify where the call to
     `assert' was made.  When using the GNU C compiler, the name of the
     function which calls `assert' is taken from the built-in variable
     `__PRETTY_FUNCTION__'; with older compilers, the function name and
     following colon are omitted.

     If the preprocessor macro `NDEBUG' is defined before `assert.h' is
     included, the `assert' macro is defined to do absolutely nothing.

     *Warning:* Even the argument expression EXPRESSION is not
     evaluated if `NDEBUG' is in effect.  So never use `assert' with
     arguments that involve side effects.  For example, `assert (++i >
     0);' is a bad idea, because `i' will not be incremented if
     `NDEBUG' is defined.

   Sometimes the "impossible" condition you want to check for is an
error return from an operating system function.  Then it is useful to
display not only where the program crashes, but also what error was
returned.  The `assert_perror' macro makes this easy.

 - Macro: void assert_perror (int ERRNUM)
     Similar to `assert', but verifies that ERRNUM is zero.

     If `NDEBUG' is defined, `assert_perror' tests the value of ERRNUM.
     If it is nonzero, `assert_perror' aborts the program after
     printing a message of the form:

          `FILE':LINENUM: FUNCTION: ERROR TEXT

     on the standard error stream.  The file name, line number, and
     function name are as for `assert'.  The error text is the result of
     `strerror (ERRNUM)'.  *Note Error Messages::.

     Like `assert', if `NDEBUG' is defined before `assert.h' is
     included, the `assert_perror' macro does absolutely nothing.  It
     does not evaluate the argument, so ERRNUM should not have any side
     effects.  It is best for ERRNUM to be just a simple variable
     reference; often it will be `errno'.

     This macro is a GNU extension.

   *Usage note:* The `assert' facility is designed for detecting
_internal inconsistency_; it is not suitable for reporting invalid
input or improper usage by the _user_ of the program.

   The information in the diagnostic messages printed by the `assert'
and `assert_perror' macro is intended to help you, the programmer,
track down the cause of a bug, but is not really useful for telling a
user of your program why his or her input was invalid or why a command
could not be carried out.  What's more, your program should not abort
when given invalid input, as `assert' would do--it should exit with
nonzero status (*note Exit Status::) after printing its error messages,
or perhaps read another command or move on to the next input file.

   *Note Error Messages::, for information on printing error messages
for problems that _do not_ represent bugs in the program.


File: libc.info,  Node: Variadic Functions,  Next: Null Pointer Constant,  Prev: Consistency Checking,  Up: Language Features

Variadic Functions
==================

   ISO C defines a syntax for declaring a function to take a variable
number or type of arguments.  (Such functions are referred to as
"varargs functions" or "variadic functions".)  However, the language
itself provides no mechanism for such functions to access their
non-required arguments; instead, you use the variable arguments macros
defined in `stdarg.h'.

   This section describes how to declare variadic functions, how to
write them, and how to call them properly.

   *Compatibility Note:* Many older C dialects provide a similar, but
incompatible, mechanism for defining functions with variable numbers of
arguments, using `varargs.h'.

* Menu:

* Why Variadic::                Reasons for making functions take
                                 variable arguments.
* How Variadic::                How to define and call variadic functions.
* Variadic Example::            A complete example.


File: libc.info,  Node: Why Variadic,  Next: How Variadic,  Up: Variadic Functions

Why Variadic Functions are Used
-------------------------------

   Ordinary C functions take a fixed number of arguments.  When you
define a function, you specify the data type for each argument.  Every
call to the function should supply the expected number of arguments,
with types that can be converted to the specified ones.  Thus, if the
function `foo' is declared with `int foo (int, char *);' then you must
call it with two arguments, a number (any kind will do) and a string
pointer.

   But some functions perform operations that can meaningfully accept an
unlimited number of arguments.

   In some cases a function can handle any number of values by
operating on all of them as a block.  For example, consider a function
that allocates a one-dimensional array with `malloc' to hold a
specified set of values.  This operation makes sense for any number of
values, as long as the length of the array corresponds to that number.
Without facilities for variable arguments, you would have to define a
separate function for each possible array size.

   The library function `printf' (*note Formatted Output::) is an
example of another class of function where variable arguments are
useful.  This function prints its arguments (which can vary in type as
well as number) under the control of a format template string.

   These are good reasons to define a "variadic" function which can
handle as many arguments as the caller chooses to pass.

   Some functions such as `open' take a fixed set of arguments, but
occasionally ignore the last few.  Strict adherence to ISO C requires
these functions to be defined as variadic; in practice, however, the GNU
C compiler and most other C compilers let you define such a function to
take a fixed set of arguments--the most it can ever use--and then only
_declare_ the function as variadic (or not declare its arguments at
all!).


File: libc.info,  Node: How Variadic,  Next: Variadic Example,  Prev: Why Variadic,  Up: Variadic Functions

How Variadic Functions are Defined and Used
-------------------------------------------

   Defining and using a variadic function involves three steps:

   * _Define_ the function as variadic, using an ellipsis (`...') in
     the argument list, and using special macros to access the variable
     arguments.  *Note Receiving Arguments::.

   * _Declare_ the function as variadic, using a prototype with an
     ellipsis (`...'), in all the files which call it.  *Note Variadic
     Prototypes::.

   * _Call_ the function by writing the fixed arguments followed by the
     additional variable arguments.  *Note Calling Variadics::.

* Menu:

* Variadic Prototypes::  How to make a prototype for a function
			  with variable arguments.
* Receiving Arguments::  Steps you must follow to access the
			  optional argument values.
* How Many Arguments::   How to decide whether there are more arguments.
* Calling Variadics::    Things you need to know about calling
			  variable arguments functions.
* Argument Macros::      Detailed specification of the macros
        		  for accessing variable arguments.
* Old Varargs::		 The pre-ISO way of defining variadic functions.


File: libc.info,  Node: Variadic Prototypes,  Next: Receiving Arguments,  Up: How Variadic

Syntax for Variable Arguments
.............................

   A function that accepts a variable number of arguments must be
declared with a prototype that says so.   You write the fixed arguments
as usual, and then tack on `...' to indicate the possibility of
additional arguments.  The syntax of ISO C requires at least one fixed
argument before the `...'.  For example,

     int
     func (const char *a, int b, ...)
     {
       ...
     }

defines a function `func' which returns an `int' and takes two required
arguments, a `const char *' and an `int'.  These are followed by any
number of anonymous arguments.

   *Portability note:* For some C compilers, the last required argument
must not be declared `register' in the function definition.
Furthermore, this argument's type must be "self-promoting": that is,
the default promotions must not change its type.  This rules out array
and function types, as well as `float', `char' (whether signed or not)
and `short int' (whether signed or not).  This is actually an ISO C
requirement.


File: libc.info,  Node: Receiving Arguments,  Next: How Many Arguments,  Prev: Variadic Prototypes,  Up: How Variadic

Receiving the Argument Values
.............................

   Ordinary fixed arguments have individual names, and you can use these
names to access their values.  But optional arguments have no
names--nothing but `...'.  How can you access them?

   The only way to access them is sequentially, in the order they were
written, and you must use special macros from `stdarg.h' in the
following three step process:

  1. You initialize an argument pointer variable of type `va_list' using
     `va_start'.  The argument pointer when initialized points to the
     first optional argument.

  2. You access the optional arguments by successive calls to `va_arg'.
     The first call to `va_arg' gives you the first optional argument,
     the next call gives you the second, and so on.

     You can stop at any time if you wish to ignore any remaining
     optional arguments.  It is perfectly all right for a function to
     access fewer arguments than were supplied in the call, but you
     will get garbage values if you try to access too many arguments.

  3. You indicate that you are finished with the argument pointer
     variable by calling `va_end'.

     (In practice, with most C compilers, calling `va_end' does nothing.
     This is always true in the GNU C compiler.  But you might as well
     call `va_end' just in case your program is someday compiled with a
     peculiar compiler.)

   *Note Argument Macros::, for the full definitions of `va_start',
`va_arg' and `va_end'.

   Steps 1 and 3 must be performed in the function that accepts the
optional arguments.  However, you can pass the `va_list' variable as an
argument to another function and perform all or part of step 2 there.

   You can perform the entire sequence of three steps multiple times
within a single function invocation.  If you want to ignore the optional
arguments, you can do these steps zero times.

   You can have more than one argument pointer variable if you like.
You can initialize each variable with `va_start' when you wish, and
then you can fetch arguments with each argument pointer as you wish.
Each argument pointer variable will sequence through the same set of
argument values, but at its own pace.

   *Portability note:* With some compilers, once you pass an argument
pointer value to a subroutine, you must not keep using the same
argument pointer value after that subroutine returns.  For full
portability, you should just pass it to `va_end'.  This is actually an
ISO C requirement, but most ANSI C compilers work happily regardless.


File: libc.info,  Node: How Many Arguments,  Next: Calling Variadics,  Prev: Receiving Arguments,  Up: How Variadic

How Many Arguments Were Supplied
................................

   There is no general way for a function to determine the number and
type of the optional arguments it was called with.  So whoever designs
the function typically designs a convention for the caller to specify
the number and type of arguments.  It is up to you to define an
appropriate calling convention for each variadic function, and write
all calls accordingly.

   One kind of calling convention is to pass the number of optional
arguments as one of the fixed arguments.  This convention works provided
all of the optional arguments are of the same type.

   A similar alternative is to have one of the required arguments be a
bit mask, with a bit for each possible purpose for which an optional
argument might be supplied.  You would test the bits in a predefined
sequence; if the bit is set, fetch the value of the next argument,
otherwise use a default value.

   A required argument can be used as a pattern to specify both the
number and types of the optional arguments.  The format string argument
to `printf' is one example of this (*note Formatted Output Functions::).

   Another possibility is to pass an "end marker" value as the last
optional argument.  For example, for a function that manipulates an
arbitrary number of pointer arguments, a null pointer might indicate the
end of the argument list.  (This assumes that a null pointer isn't
otherwise meaningful to the function.)  The `execl' function works in
just this way; see *Note Executing a File::.


File: libc.info,  Node: Calling Variadics,  Next: Argument Macros,  Prev: How Many Arguments,  Up: How Variadic

Calling Variadic Functions
..........................

   You don't have to do anything special to call a variadic function.
Just put the arguments (required arguments, followed by optional ones)
inside parentheses, separated by commas, as usual.  But you must declare
the function with a prototype and know how the argument values are
converted.

   In principle, functions that are _defined_ to be variadic must also
be _declared_ to be variadic using a function prototype whenever you
call them.  (*Note Variadic Prototypes::, for how.)  This is because
some C compilers use a different calling convention to pass the same set
of argument values to a function depending on whether that function
takes variable arguments or fixed arguments.

   In practice, the GNU C compiler always passes a given set of argument
types in the same way regardless of whether they are optional or
required.  So, as long as the argument types are self-promoting, you can
safely omit declaring them.  Usually it is a good idea to declare the
argument types for variadic functions, and indeed for all functions.
But there are a few functions which it is extremely convenient not to
have to declare as variadic--for example, `open' and `printf'.

   Since the prototype doesn't specify types for optional arguments, in
a call to a variadic function the "default argument promotions" are
performed on the optional argument values.  This means the objects of
type `char' or `short int' (whether signed or not) are promoted to
either `int' or `unsigned int', as appropriate; and that objects of
type `float' are promoted to type `double'.  So, if the caller passes a
`char' as an optional argument, it is promoted to an `int', and the
function can access it with `va_arg (AP, int)'.

   Conversion of the required arguments is controlled by the function
prototype in the usual way: the argument expression is converted to the
declared argument type as if it were being assigned to a variable of
that type.


File: libc.info,  Node: Argument Macros,  Next: Old Varargs,  Prev: Calling Variadics,  Up: How Variadic

Argument Access Macros
......................

   Here are descriptions of the macros used to retrieve variable
arguments.  These macros are defined in the header file `stdarg.h'.

 - Data Type: va_list
     The type `va_list' is used for argument pointer variables.

 - Macro: void va_start (va_list AP, LAST-REQUIRED)
     This macro initializes the argument pointer variable AP to point
     to the first of the optional arguments of the current function;
     LAST-REQUIRED must be the last required argument to the function.

     *Note Old Varargs::, for an alternate definition of `va_start'
     found in the header file `varargs.h'.

 - Macro: TYPE va_arg (va_list AP, TYPE)
     The `va_arg' macro returns the value of the next optional argument,
     and modifies the value of AP to point to the subsequent argument.
     Thus, successive uses of `va_arg' return successive optional
     arguments.

     The type of the value returned by `va_arg' is TYPE as specified in
     the call.  TYPE must be a self-promoting type (not `char' or
     `short int' or `float') that matches the type of the actual
     argument.

 - Macro: void va_end (va_list AP)
     This ends the use of AP.  After a `va_end' call, further `va_arg'
     calls with the same AP may not work.  You should invoke `va_end'
     before returning from the function in which `va_start' was invoked
     with the same AP argument.

     In the GNU C library, `va_end' does nothing, and you need not ever
     use it except for reasons of portability.


   Sometimes it is necessary to parse the list of parameters more than
once or one wants to remember a certain position in the parameter list.
To do this, one will have to make a copy of the current value of the
argument.  But `va_list' is an opaque type and one cannot necessarily
assign the value of one variable of type `va_list' to another variable
of the same type.

 - Macro: void __va_copy (va_list DEST, va_list SRC)
     The `__va_copy' macro allows copying of objects of type `va_list'
     even if this is not an integral type.  The argument pointer in
     DEST is initialized to point to the same argument as the pointer
     in SRC.

     This macro is a GNU extension but it will hopefully also be
     available in the next update of the ISO C standard.

   If you want to use `__va_copy' you should always be prepared for the
possibility that this macro will not be available.  On architectures
where a simple assignment is invalid, hopefully `__va_copy' _will_ be
available, so one should always write something like this:

     {
       va_list ap, save;
       ...
     #ifdef __va_copy
       __va_copy (save, ap);
     #else
       save = ap;
     #endif
       ...
     }


File: libc.info,  Node: Variadic Example,  Prev: How Variadic,  Up: Variadic Functions

Example of a Variadic Function
------------------------------

   Here is a complete sample function that accepts a variable number of
arguments.  The first argument to the function is the count of remaining
arguments, which are added up and the result returned.  While trivial,
this function is sufficient to illustrate how to use the variable
arguments facility.

     #include <stdarg.h>
     #include <stdio.h>
     
     int
     add_em_up (int count,...)
     {
       va_list ap;
       int i, sum;
     
       va_start (ap, count);         /* Initialize the argument list. */
     
       sum = 0;
       for (i = 0; i < count; i++)
         sum += va_arg (ap, int);    /* Get the next argument value. */
     
       va_end (ap);                  /* Clean up. */
       return sum;
     }
     
     int
     main (void)
     {
       /* This call prints 16. */
       printf ("%d\n", add_em_up (3, 5, 5, 6));
     
       /* This call prints 55. */
       printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
     
       return 0;
     }


File: libc.info,  Node: Old Varargs,  Prev: Argument Macros,  Up: How Variadic

Old-Style Variadic Functions
............................

   Before ISO C, programmers used a slightly different facility for
writing variadic functions.  The GNU C compiler still supports it;
currently, it is more portable than the ISO C facility, since support
for ISO C is still not universal.  The header file which defines the
old-fashioned variadic facility is called `varargs.h'.

   Using `varargs.h' is almost the same as using `stdarg.h'.  There is
no difference in how you call a variadic function; see *Note Calling
Variadics::.  The only difference is in how you define them.  First of
all, you must use old-style non-prototype syntax, like this:

     tree
     build (va_alist)
          va_dcl
     {

   Secondly, you must give `va_start' only one argument, like this:

       va_list p;
       va_start (p);

   These are the special macros used for defining old-style variadic
functions:

 - Macro: va_alist
     This macro stands for the argument name list required in a variadic
     function.

 - Macro: va_dcl
     This macro declares the implicit argument or arguments for a
     variadic function.

 - Macro: void va_start (va_list AP)
     This macro, as defined in `varargs.h', initializes the argument
     pointer variable AP to point to the first argument of the current
     function.

   The other argument macros, `va_arg' and `va_end', are the same in
`varargs.h' as in `stdarg.h'; see *Note Argument Macros::, for details.

   It does not work to include both `varargs.h' and `stdarg.h' in the
same compilation; they define `va_start' in conflicting ways.


File: libc.info,  Node: Null Pointer Constant,  Next: Important Data Types,  Prev: Variadic Functions,  Up: Language Features

Null Pointer Constant
=====================

   The null pointer constant is guaranteed not to point to any real
object.  You can assign it to any pointer variable since it has type
`void *'.  The preferred way to write a null pointer constant is with
`NULL'.

 - Macro: void * NULL
     This is a null pointer constant.

   You can also use `0' or `(void *)0' as a null pointer constant, but
using `NULL' is cleaner because it makes the purpose of the constant
more evident.

   If you use the null pointer constant as a function argument, then for
complete portability you should make sure that the function has a
prototype declaration.  Otherwise, if the target machine has two
different pointer representations, the compiler won't know which
representation to use for that argument.  You can avoid the problem by
explicitly casting the constant to the proper pointer type, but we
recommend instead adding a prototype for the function you are calling.


File: libc.info,  Node: Important Data Types,  Next: Data Type Measurements,  Prev: Null Pointer Constant,  Up: Language Features

Important Data Types
====================

   The result of subtracting two pointers in C is always an integer,
but the precise data type varies from C compiler to C compiler.
Likewise, the data type of the result of `sizeof' also varies between
compilers.  ISO defines standard aliases for these two types, so you
can refer to them in a portable fashion.  They are defined in the
header file `stddef.h'.

 - Data Type: ptrdiff_t
     This is the signed integer type of the result of subtracting two
     pointers.  For example, with the declaration `char *p1, *p2;', the
     expression `p2 - p1' is of type `ptrdiff_t'.  This will probably
     be one of the standard signed integer types (`short int', `int' or
     `long int'), but might be a nonstandard type that exists only for
     this purpose.

 - Data Type: size_t
     This is an unsigned integer type used to represent the sizes of
     objects.  The result of the `sizeof' operator is of this type, and
     functions such as `malloc' (*note Unconstrained Allocation::) and
     `memcpy' (*note Copying and Concatenation::) accept arguments of
     this type to specify object sizes.

     *Usage Note:* `size_t' is the preferred way to declare any
     arguments or variables that hold the size of an object.

   In the GNU system `size_t' is equivalent to either `unsigned int' or
`unsigned long int'.  These types have identical properties on the GNU
system and, for most purposes, you can use them interchangeably.
However, they are distinct as data types, which makes a difference in
certain contexts.

   For example, when you specify the type of a function argument in a
function prototype, it makes a difference which one you use.  If the
system header files declare `malloc' with an argument of type `size_t'
and you declare `malloc' with an argument of type `unsigned int', you
will get a compilation error if `size_t' happens to be `unsigned long
int' on your system.  To avoid any possibility of error, when a
function argument or value is supposed to have type `size_t', never
declare its type in any other way.

   *Compatibility Note:* Implementations of C before the advent of
ISO C generally used `unsigned int' for representing object sizes and
`int' for pointer subtraction results.  They did not necessarily define
either `size_t' or `ptrdiff_t'.  Unix systems did define `size_t', in
`sys/types.h', but the definition was usually a signed type.


File: libc.info,  Node: Data Type Measurements,  Prev: Important Data Types,  Up: Language Features

Data Type Measurements
======================

   Most of the time, if you choose the proper C data type for each
object in your program, you need not be concerned with just how it is
represented or how many bits it uses.  When you do need such
information, the C language itself does not provide a way to get it.
The header files `limits.h' and `float.h' contain macros which give you
this information in full detail.

* Menu:

* Width of Type::           How many bits does an integer type hold?
* Range of Type::           What are the largest and smallest values
			     that an integer type can hold?
* Floating Type Macros::    Parameters that measure the floating point types.
* Structure Measurement::   Getting measurements on structure types.


File: libc.info,  Node: Width of Type,  Next: Range of Type,  Up: Data Type Measurements

Computing the Width of an Integer Data Type
-------------------------------------------

   The most common reason that a program needs to know how many bits
are in an integer type is for using an array of `long int' as a bit
vector.  You can access the bit at index N with

     vector[N / LONGBITS] & (1 << (N % LONGBITS))

provided you define `LONGBITS' as the number of bits in a `long int'.

   There is no operator in the C language that can give you the number
of bits in an integer data type.  But you can compute it from the macro
`CHAR_BIT', defined in the header file `limits.h'.

`CHAR_BIT'
     This is the number of bits in a `char'--eight, on most systems.
     The value has type `int'.

     You can compute the number of bits in any data type TYPE like this:

          sizeof (TYPE) * CHAR_BIT


File: libc.info,  Node: Range of Type,  Next: Floating Type Macros,  Prev: Width of Type,  Up: Data Type Measurements

Range of an Integer Type
------------------------

   Suppose you need to store an integer value which can range from zero
to one million.  Which is the smallest type you can use?  There is no
general rule; it depends on the C compiler and target machine.  You can
use the `MIN' and `MAX' macros in `limits.h' to determine which type
will work.

   Each signed integer type has a pair of macros which give the smallest
and largest values that it can hold.  Each unsigned integer type has one
such macro, for the maximum value; the minimum value is, of course,
zero.

   The values of these macros are all integer constant expressions.  The
`MAX' and `MIN' macros for `char' and `short int' types have values of
type `int'.  The `MAX' and `MIN' macros for the other types have values
of the same type described by the macro--thus, `ULONG_MAX' has type
`unsigned long int'.

`SCHAR_MIN'
     This is the minimum value that can be represented by a
     `signed char'.

`SCHAR_MAX'
`UCHAR_MAX'
     These are the maximum values that can be represented by a
     `signed char' and `unsigned char', respectively.

`CHAR_MIN'
     This is the minimum value that can be represented by a `char'.
     It's equal to `SCHAR_MIN' if `char' is signed, or zero otherwise.

`CHAR_MAX'
     This is the maximum value that can be represented by a `char'.
     It's equal to `SCHAR_MAX' if `char' is signed, or `UCHAR_MAX'
     otherwise.

`SHRT_MIN'
     This is the minimum value that can be represented by a
     `signed short int'.  On most machines that the GNU C library runs
     on, `short' integers are 16-bit quantities.

`SHRT_MAX'
`USHRT_MAX'
     These are the maximum values that can be represented by a
     `signed short int' and `unsigned short int', respectively.

`INT_MIN'
     This is the minimum value that can be represented by a
     `signed int'.  On most machines that the GNU C system runs on, an
     `int' is a 32-bit quantity.

`INT_MAX'
`UINT_MAX'
     These are the maximum values that can be represented by,
     respectively, the type `signed int' and the type `unsigned int'.

`LONG_MIN'
     This is the minimum value that can be represented by a
     `signed long int'.  On most machines that the GNU C system runs
     on, `long' integers are 32-bit quantities, the same size as `int'.

`LONG_MAX'
`ULONG_MAX'
     These are the maximum values that can be represented by a
     `signed long int' and `unsigned long int', respectively.

`LONG_LONG_MIN'
     This is the minimum value that can be represented by a
     `signed long long int'.  On most machines that the GNU C system
     runs on, `long long' integers are 64-bit quantities.

`LONG_LONG_MAX'
`ULONG_LONG_MAX'
     These are the maximum values that can be represented by a `signed
     long long int' and `unsigned long long int', respectively.

`WCHAR_MAX'
     This is the maximum value that can be represented by a `wchar_t'.
     *Note Extended Char Intro::.

   The header file `limits.h' also defines some additional constants
that parameterize various operating system and file system limits.
These constants are described in *Note System Configuration::.


File: libc.info,  Node: Floating Type Macros,  Next: Structure Measurement,  Prev: Range of Type,  Up: Data Type Measurements

Floating Type Macros
--------------------

   The specific representation of floating point numbers varies from
machine to machine.  Because floating point numbers are represented
internally as approximate quantities, algorithms for manipulating
floating point data often need to take account of the precise details of
the machine's floating point representation.

   Some of the functions in the C library itself need this information;
for example, the algorithms for printing and reading floating point
numbers (*note I/O on Streams::) and for calculating trigonometric and
irrational functions (*note Mathematics::) use it to avoid round-off
error and loss of accuracy.  User programs that implement numerical
analysis techniques also often need this information in order to
minimize or compute error bounds.

   The header file `float.h' describes the format used by your machine.

* Menu:

* Floating Point Concepts::     Definitions of terminology.
* Floating Point Parameters::   Details of specific macros.
* IEEE Floating Point::         The measurements for one common
                                 representation.

