Mon Dec 18 13:40:37 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu>
[glibc.git] / manual / lang.texi
blob66d41846d2caeb61a5ff1983ff6399f3bac36dab
1 @node Language Features, Library Summary, System Configuration, Top
2 @appendix C Language Facilities in the Library
4 Some of the facilities implemented by the C library really should be
5 thought of as parts of the C language itself.  These facilities ought to
6 be documented in the C Language Manual, not in the library manual; but
7 since we don't have the language manual yet, and documentation for these
8 features has been written, we are publishing it here.
10 @menu
11 * Consistency Checking::        Using @code{assert} to abort if
12                                  something ``impossible'' happens.
13 * Variadic Functions::          Defining functions with varying numbers
14                                  of args. 
15 * Null Pointer Constant::       The macro @code{NULL}.
16 * Important Data Types::        Data types for object sizes.
17 * Data Type Measurements::      Parameters of data type representations.
18 @end menu
20 @node Consistency Checking
21 @section Explicitly Checking Internal Consistency
22 @cindex consistency checking
23 @cindex impossible events
24 @cindex assertions
26 When you're writing a program, it's often a good idea to put in checks
27 at strategic places for ``impossible'' errors or violations of basic
28 assumptions.  These checks are helpful in debugging problems due to
29 misunderstandings between different parts of the program.
31 @pindex assert.h
32 The @code{assert} macro, defined in the header file @file{assert.h},
33 provides a convenient way to abort the program while printing a message
34 about where in the program the error was detected.
36 @vindex NDEBUG
37 Once you think your program is debugged, you can disable the error
38 checks performed by the @code{assert} macro by recompiling with the
39 macro @code{NDEBUG} defined.  This means you don't actually have to
40 change the program source code to disable these checks.
42 But disabling these consistency checks is undesirable unless they make
43 the program significantly slower.  All else being equal, more error
44 checking is good no matter who is running the program.  A wise user
45 would rather have a program crash, visibly, than have it return nonsense
46 without indicating anything might be wrong.
48 @comment assert.h
49 @comment ANSI
50 @deftypefn Macro void assert (int @var{expression})
51 Verify the programmer's belief that @var{expression} should be nonzero
52 at this point in the program.
54 If @code{NDEBUG} is not defined, @code{assert} tests the value of
55 @var{expression}.  If it is false (zero), @code{assert} aborts the
56 program (@pxref{Aborting a Program}) after printing a message of the
57 form:
59 @smallexample
60 @file{@var{file}}:@var{linenum}: Assertion `@var{expression}' failed.
61 @end smallexample
63 @noindent
64 on the standard error stream @code{stderr} (@pxref{Standard Streams}).
65 The filename and line number are taken from the C preprocessor macros
66 @code{__FILE__} and @code{__LINE__} and specify where the call to
67 @code{assert} was written.
69 If the preprocessor macro @code{NDEBUG} is defined at the point where
70 @file{assert.h} is included, the @code{assert} macro is defined to do
71 absolutely nothing.
73 @strong{Warning:} Even the argument expression @var{expression} is not
74 evaluated if @code{NDEBUG} is in effect.  So never use @code{assert}
75 with arguments that involve side effects.  For example, @code{assert
76 (++i > 0);} is a bad idea, because @code{i} will not be incremented if
77 @code{NDEBUG} is defined.
78 @end deftypefn
80 @strong{Usage note:} The @code{assert} facility is designed for
81 detecting @emph{internal inconsistency}; it is not suitable for
82 reporting invalid input or improper usage by @emph{the user} of the
83 program.
85 The information in the diagnostic messages printed by the @code{assert}
86 macro is intended to help you, the programmer, track down the cause of a
87 bug, but is not really useful for telling a user of your program why his
88 or her input was invalid or why a command could not be carried out.  So
89 you can't use @code{assert} to print the error messages for these
90 eventualities.
92 What's more, your program should not abort when given invalid input, as
93 @code{assert} would do---it should exit with nonzero status (@pxref{Exit
94 Status}) after printing its error messages, or perhaps read another
95 command or move on to the next input file.
97 @xref{Error Messages}, for information on printing error messages for
98 problems that @emph{do not} represent bugs in the program.
101 @node Variadic Functions
102 @section Variadic Functions
103 @cindex variable number of arguments
104 @cindex variadic functions
105 @cindex optional arguments
107 ANSI C defines a syntax for declaring a function to take a variable
108 number or type of arguments.  (Such functions are referred to as
109 @dfn{varargs functions} or @dfn{variadic functions}.)  However, the
110 language itself provides no mechanism for such functions to access their
111 non-required arguments; instead, you use the variable arguments macros
112 defined in @file{stdarg.h}.
114 This section describes how to declare variadic functions, how to write
115 them, and how to call them properly.
117 @strong{Compatibility Note:} Many older C dialects provide a similar,
118 but incompatible, mechanism for defining functions with variable numbers
119 of arguments, using @file{varargs.h}.
121 @menu
122 * Why Variadic::                Reasons for making functions take
123                                  variable arguments. 
124 * How Variadic::                How to define and call variadic functions.
125 * Variadic Example::            A complete example.
126 @end menu
128 @node Why Variadic
129 @subsection Why Variadic Functions are Used
131 Ordinary C functions take a fixed number of arguments.  When you define
132 a function, you specify the data type for each argument.  Every call to
133 the function should supply the expected number of arguments, with types
134 that can be converted to the specified ones.  Thus, if the function
135 @samp{foo} is declared with @code{int foo (int, char *);} then you must
136 call it with two arguments, a number (any kind will do) and a string
137 pointer.
139 But some functions perform operations that can meaningfully accept an
140 unlimited number of arguments.
142 In some cases a function can handle any number of values by operating on
143 all of them as a block.  For example, consider a function that allocates
144 a one-dimensional array with @code{malloc} to hold a specified set of
145 values.  This operation makes sense for any number of values, as long as
146 the length of the array corresponds to that number.  Without facilities
147 for variable arguments, you would have to define a separate function for
148 each possible array size.
150 The library function @code{printf} (@pxref{Formatted Output}) is an
151 example of another class of function where variable arguments are
152 useful.  This function prints its arguments (which can vary in type as
153 well as number) under the control of a format template string.
155 These are good reasons to define a @dfn{variadic} function which can
156 handle as many arguments as the caller chooses to pass.
158 Some functions such as @code{open} take a fixed set of arguments, but
159 occasionally ignore the last few.  Strict adherence to ANSI C requires
160 these functions to be defined as variadic; in practice, however, the GNU
161 C compiler and most other C compilers let you define such a function to
162 take a fixed set of arguments---the most it can ever use---and then only
163 @emph{declare} the function as variadic (or not declare its arguments
164 at all!).
166 @node How Variadic
167 @subsection How Variadic Functions are Defined and Used
169 Defining and using a variadic function involves three steps:
171 @itemize @bullet
172 @item
173 @emph{Define} the function as variadic, using an ellipsis
174 (@samp{@dots{}}) in the argument list, and using special macros to
175 access the variable arguments.  @xref{Receiving Arguments}.
177 @item
178 @emph{Declare} the function as variadic, using a prototype with an
179 ellipsis (@samp{@dots{}}), in all the files which call it.
180 @xref{Variadic Prototypes}.
182 @item
183 @emph{Call} the function by writing the fixed arguments followed by the
184 additional variable arguments.  @xref{Calling Variadics}.
185 @end itemize
187 @menu
188 * Variadic Prototypes::  How to make a prototype for a function
189                           with variable arguments.
190 * Receiving Arguments::  Steps you must follow to access the
191                           optional argument values.
192 * How Many Arguments::   How to decide whether there are more arguments. 
193 * Calling Variadics::    Things you need to know about calling
194                           variable arguments functions.
195 * Argument Macros::      Detailed specification of the macros
196                           for accessing variable arguments.
197 * Old Varargs::          The pre-ANSI way of defining variadic functions.
198 @end menu
200 @node Variadic Prototypes
201 @subsubsection Syntax for Variable Arguments
202 @cindex function prototypes (variadic)
203 @cindex prototypes for variadic functions
204 @cindex variadic function prototypes
206 A function that accepts a variable number of arguments must be declared
207 with a prototype that says so.   You write the fixed arguments as usual,
208 and then tack on @samp{@dots{}} to indicate the possibility of 
209 additional arguments.  The syntax of ANSI C requires at least one fixed
210 argument before the @samp{@dots{}}.  For example,
212 @smallexample
213 int 
214 func (const char *a, int b, @dots{})
216   @dots{}
217 @}      
218 @end smallexample
220 @noindent
221 outlines a definition of a function @code{func} which returns an
222 @code{int} and takes two required arguments, a @code{const char *} and
223 an @code{int}.  These are followed by any number of anonymous
224 arguments.
226 @strong{Portability note:} For some C compilers, the last required
227 argument must not be declared @code{register} in the function
228 definition.  Furthermore, this argument's type must be
229 @dfn{self-promoting}: that is, the default promotions must not change
230 its type.  This rules out array and function types, as well as
231 @code{float}, @code{char} (whether signed or not) and @w{@code{short int}}
232 (whether signed or not).  This is actually an ANSI C requirement.
234 @node Receiving Arguments
235 @subsubsection Receiving the Argument Values
236 @cindex variadic function argument access
237 @cindex arguments (variadic functions)
239 Ordinary fixed arguments have individual names, and you can use these
240 names to access their values.  But optional arguments have no
241 names---nothing but @samp{@dots{}}.  How can you access them?
243 @pindex stdarg.h
244 The only way to access them is sequentially, in the order they were
245 written, and you must use special macros from @file{stdarg.h} in the
246 following three step process:
248 @enumerate
249 @item
250 You initialize an argument pointer variable of type @code{va_list} using
251 @code{va_start}.  The argument pointer when initialized points to the
252 first optional argument.
254 @item
255 You access the optional arguments by successive calls to @code{va_arg}.
256 The first call to @code{va_arg} gives you the first optional argument,
257 the next call gives you the second, and so on.
259 You can stop at any time if you wish to ignore any remaining optional
260 arguments.  It is perfectly all right for a function to access fewer
261 arguments than were supplied in the call, but you will get garbage
262 values if you try to access too many arguments.
264 @item
265 You indicate that you are finished with the argument pointer variable by
266 calling @code{va_end}.
268 (In practice, with most C compilers, calling @code{va_end} does nothing
269 and you do not really need to call it.  This is always true in the GNU C
270 compiler.  But you might as well call @code{va_end} just in case your
271 program is someday compiled with a peculiar compiler.)
272 @end enumerate
274 @xref{Argument Macros}, for the full definitions of @code{va_start}, 
275 @code{va_arg} and @code{va_end}.
277 Steps 1 and 3 must be performed in the function that accepts the
278 optional arguments.  However, you can pass the @code{va_list} variable
279 as an argument to another function and perform all or part of step 2
280 there.
282 You can perform the entire sequence of the three steps multiple times
283 within a single function invocation.  If you want to ignore the optional
284 arguments, you can do these steps zero times.
286 You can have more than one argument pointer variable if you like.  You
287 can initialize each variable with @code{va_start} when you wish, and
288 then you can fetch arguments with each argument pointer as you wish.
289 Each argument pointer variable will sequence through the same set of
290 argument values, but at its own pace.
292 @strong{Portability note:} With some compilers, once you pass an
293 argument pointer value to a subroutine, you must not keep using the same
294 argument pointer value after that subroutine returns.  For full
295 portability, you should just pass it to @code{va_end}.  This is actually
296 an ANSI C requirement, but most ANSI C compilers work happily
297 regardless.
299 @node How Many Arguments
300 @subsubsection How Many Arguments Were Supplied
301 @cindex number of arguments passed
302 @cindex how many arguments
303 @cindex arguments, how many
305 There is no general way for a function to determine the number and type
306 of the optional arguments it was called with.  So whoever designs the
307 function typically designs a convention for the caller to tell it how
308 many arguments it has, and what kind.  It is up to you to define an
309 appropriate calling convention for each variadic function, and write all
310 calls accordingly.
312 One kind of calling convention is to pass the number of optional
313 arguments as one of the fixed arguments.  This convention works provided
314 all of the optional arguments are of the same type.
316 A similar alternative is to have one of the required arguments be a bit
317 mask, with a bit for each possible purpose for which an optional
318 argument might be supplied.  You would test the bits in a predefined
319 sequence; if the bit is set, fetch the value of the next argument,
320 otherwise use a default value.
322 A required argument can be used as a pattern to specify both the number
323 and types of the optional arguments.  The format string argument to
324 @code{printf} is one example of this (@pxref{Formatted Output Functions}).
326 Another possibility is to pass an ``end marker'' value as the last
327 optional argument.  For example, for a function that manipulates an
328 arbitrary number of pointer arguments, a null pointer might indicate the
329 end of the argument list.  (This assumes that a null pointer isn't
330 otherwise meaningful to the function.)  The @code{execl} function works
331 in just this way; see @ref{Executing a File}.
334 @node Calling Variadics
335 @subsubsection Calling Variadic Functions
336 @cindex variadic functions, calling
337 @cindex calling variadic functions
338 @cindex declaring variadic functions
340 You don't have to write anything special when you call a variadic function.
341 Just write the arguments (required arguments, followed by optional ones)
342 inside parentheses, separated by commas, as usual.  But you should prepare
343 by declaring the function with a prototype, and you must know how the
344 argument values are converted.
346 In principle, functions that are @emph{defined} to be variadic must also
347 be @emph{declared} to be variadic using a function prototype whenever
348 you call them.  (@xref{Variadic Prototypes}, for how.)  This is because
349 some C compilers use a different calling convention to pass the same set
350 of argument values to a function depending on whether that function
351 takes variable arguments or fixed arguments.
353 In practice, the GNU C compiler always passes a given set of argument
354 types in the same way regardless of whether they are optional or
355 required.  So, as long as the argument types are self-promoting, you can
356 safely omit declaring them.  Usually it is a good idea to declare the
357 argument types for variadic functions, and indeed for all functions.
358 But there are a few functions which it is extremely convenient not to
359 have to declare as variadic---for example, @code{open} and
360 @code{printf}.
362 @cindex default argument promotions
363 @cindex argument promotion
364 Since the prototype doesn't specify types for optional arguments, in a
365 call to a variadic function the @dfn{default argument promotions} are
366 performed on the optional argument values.  This means the objects of
367 type @code{char} or @w{@code{short int}} (whether signed or not) are
368 promoted to either @code{int} or @w{@code{unsigned int}}, as
369 appropriate; and that objects of type @code{float} are promoted to type
370 @code{double}.  So, if the caller passes a @code{char} as an optional
371 argument, it is promoted to an @code{int}, and the function should get
372 it with @code{va_arg (@var{ap}, int)}.
374 Conversion of the required arguments is controlled by the function
375 prototype in the usual way: the argument expression is converted to the
376 declared argument type as if it were being assigned to a variable of
377 that type.
379 @node Argument Macros
380 @subsubsection Argument Access Macros
382 Here are descriptions of the macros used to retrieve variable arguments.
383 These macros are defined in the header file @file{stdarg.h}.
384 @pindex stdarg.h
386 @comment stdarg.h
387 @comment ANSI
388 @deftp {Data Type} va_list
389 The type @code{va_list} is used for argument pointer variables.
390 @end deftp
392 @comment stdarg.h
393 @comment ANSI
394 @deftypefn {Macro} void va_start (va_list @var{ap}, @var{last-required})
395 This macro initializes the argument pointer variable @var{ap} to point
396 to the first of the optional arguments of the current function;
397 @var{last-required} must be the last required argument to the function.
399 @xref{Old Varargs}, for an alternate definition of @code{va_start}
400 found in the header file @file{varargs.h}.
401 @end deftypefn
403 @comment stdarg.h
404 @comment ANSI
405 @deftypefn {Macro} @var{type} va_arg (va_list @var{ap}, @var{type})
406 The @code{va_arg} macro returns the value of the next optional argument,
407 and modifies the value of @var{ap} to point to the subsequent argument.
408 Thus, successive uses of @code{va_arg} return successive optional 
409 arguments.
411 The type of the value returned by @code{va_arg} is @var{type} as
412 specified in the call.  @var{type} must be a self-promoting type (not
413 @code{char} or @code{short int} or @code{float}) that matches the type
414 of the actual argument.
415 @end deftypefn
417 @comment stdarg.h
418 @comment ANSI
419 @deftypefn {Macro} void va_end (va_list @var{ap})
420 This ends the use of @var{ap}.  After a @code{va_end} call, further
421 @code{va_arg} calls with the same @var{ap} may not work.  You should invoke
422 @code{va_end} before returning from the function in which @code{va_start}
423 was invoked with the same @var{ap} argument.
425 In the GNU C library, @code{va_end} does nothing, and you need not ever
426 use it except for reasons of portability.
427 @refill
428 @end deftypefn
430 @node Variadic Example
431 @subsection Example of a Variadic Function
433 Here is a complete sample function that accepts a variable number of
434 arguments.  The first argument to the function is the count of remaining
435 arguments, which are added up and the result returned.  While trivial,
436 this function is sufficient to illustrate how to use the variable
437 arguments facility.
439 @comment Yes, this example has been tested.
440 @smallexample
441 @include add.c.texi
442 @end smallexample
444 @node Old Varargs
445 @subsubsection Old-Style Variadic Functions
447 @pindex varargs.h
448 Before ANSI C, programmers used a slightly different facility for
449 writing variadic functions.  The GNU C compiler still supports it;
450 currently, it is more portable than the ANSI C facility, since support
451 for ANSI C is still not universal.  The header file which defines the
452 old-fashioned variadic facility is called @file{varargs.h}.
454 Using @file{varargs.h} is almost the same as using @file{stdarg.h}.
455 There is no difference in how you call a variadic function;
456 @xref{Calling Variadics}.  The only difference is in how you define
457 them.  First of all, you must use old-style non-prototype syntax, like
458 this:
460 @smallexample
461 tree
462 build (va_alist)
463      va_dcl
465 @end smallexample
467 Secondly, you must give @code{va_start} just one argument, like this:
469 @smallexample
470   va_list p;
471   va_start (p);
472 @end smallexample
474 These are the special macros used for defining old-style variadic
475 functions:
477 @comment varargs.h
478 @comment Unix
479 @deffn Macro va_alist
480 This macro stands for the argument name list required in a variadic
481 function.  
482 @end deffn
484 @comment varargs.h
485 @comment Unix
486 @deffn Macro va_dcl
487 This macro declares the implicit argument or arguments for a variadic
488 function.
489 @end deffn
491 @comment varargs.h
492 @comment Unix
493 @deftypefn {Macro} void va_start (va_list @var{ap})
494 This macro, as defined in @file{varargs.h}, initializes the argument
495 pointer variable @var{ap} to point to the first argument of the current
496 function.
497 @end deftypefn
499 The other argument macros, @code{va_arg} and @code{va_end}, are the same
500 in @file{varargs.h} as in @file{stdarg.h}; see @ref{Argument Macros} for
501 details.
503 It does not work to include both @file{varargs.h} and @file{stdarg.h} in
504 the same compilation; they define @code{va_start} in conflicting ways.
506 @node Null Pointer Constant
507 @section Null Pointer Constant
508 @cindex null pointer constant
510 The null pointer constant is guaranteed not to point to any real object.
511 You can assign it to any pointer variable since it has type @code{void
512 *}.  The preferred way to write a null pointer constant is with
513 @code{NULL}.
515 @comment stddef.h
516 @comment ANSI
517 @deftypevr Macro {void *} NULL
518 This is a null pointer constant.
519 @end deftypevr
521 You can also use @code{0} or @code{(void *)0} as a null pointer
522 constant, but using @code{NULL} is cleaner because it makes the purpose
523 of the constant more evident.
525 If you use the null pointer constant as a function argument, then for
526 complete portability you should make sure that the function has a
527 prototype declaration.  Otherwise, if the target machine has two
528 different pointer representations, the compiler won't know which
529 representation to use for that argument.  You can avoid the problem by
530 explicitly casting the constant to the proper pointer type, but we
531 recommend instead adding a prototype for the function you are calling.
533 @node Important Data Types
534 @section Important Data Types
536 The result of subtracting two pointers in C is always an integer, but the
537 precise data type varies from C compiler to C compiler.  Likewise, the
538 data type of the result of @code{sizeof} also varies between compilers.
539 ANSI defines standard aliases for these two types, so you can refer to
540 them in a portable fashion.  They are defined in the header file 
541 @file{stddef.h}.
542 @pindex stddef.h
544 @comment stddef.h
545 @comment ANSI
546 @deftp {Data Type} ptrdiff_t
547 This is the signed integer type of the result of subtracting two
548 pointers.  For example, with the declaration @code{char *p1, *p2;}, the
549 expression @code{p2 - p1} is of type @code{ptrdiff_t}.  This will
550 probably be one of the standard signed integer types (@w{@code{short
551 int}}, @code{int} or @w{@code{long int}}), but might be a nonstandard
552 type that exists only for this purpose.
553 @end deftp
555 @comment stddef.h
556 @comment ANSI
557 @deftp {Data Type} size_t
558 This is an unsigned integer type used to represent the sizes of objects.
559 The result of the @code{sizeof} operator is of this type, and functions
560 such as @code{malloc} (@pxref{Unconstrained Allocation}) and
561 @code{memcpy} (@pxref{Copying and Concatenation}) accept arguments of
562 this type to specify object sizes.
564 @strong{Usage Note:} @code{size_t} is the preferred way to declare any
565 arguments or variables that hold the size of an object.
566 @end deftp
568 In the GNU system @code{size_t} is equivalent to either
569 @w{@code{unsigned int}} or @w{@code{unsigned long int}}.  These types
570 have identical properties on the GNU system, and for most purposes, you
571 can use them interchangeably.  However, they are distinct as data types,
572 which makes a difference in certain contexts.
574 For example, when you specify the type of a function argument in a
575 function prototype, it makes a difference which one you use.  If the
576 system header files declare @code{malloc} with an argument of type
577 @code{size_t} and you declare @code{malloc} with an argument of type
578 @code{unsigned int}, you will get a compilation error if @code{size_t}
579 happens to be @code{unsigned long int} on your system.  To avoid any
580 possibility of error, when a function argument or value is supposed to
581 have type @code{size_t}, never declare its type in any other way.
583 @strong{Compatibility Note:} Implementations of C before the advent of
584 ANSI C generally used @code{unsigned int} for representing object sizes
585 and @code{int} for pointer subtraction results.  They did not
586 necessarily define either @code{size_t} or @code{ptrdiff_t}.  Unix
587 systems did define @code{size_t}, in @file{sys/types.h}, but the
588 definition was usually a signed type.
590 @node Data Type Measurements
591 @section Data Type Measurements
593 Most of the time, if you choose the proper C data type for each object
594 in your program, you need not be concerned with just how it is
595 represented or how many bits it uses.  When you do need such
596 information, the C language itself does not provide a way to get it.
597 The header files @file{limits.h} and @file{float.h} contain macros
598 which give you this information in full detail.
600 @menu
601 * Width of Type::           How many bits does an integer type hold?
602 * Range of Type::           What are the largest and smallest values
603                              that an integer type can hold?
604 * Floating Type Macros::    Parameters that measure the floating point types. 
605 * Structure Measurement::   Getting measurements on structure types.
606 @end menu
608 @node Width of Type
609 @subsection Computing the Width of an Integer Data Type
610 @cindex integer type width
611 @cindex width of integer type
612 @cindex type measurements, integer
614 The most common reason that a program needs to know how many bits are in
615 an integer type is for using an array of @code{long int} as a bit vector.
616 You can access the bit at index @var{n} with
618 @smallexample
619 vector[@var{n} / LONGBITS] & (1 << (@var{n} % LONGBITS))
620 @end smallexample
622 @noindent
623 provided you define @code{LONGBITS} as the number of bits in a
624 @code{long int}.
626 @pindex limits.h
627 There is no operator in the C language that can give you the number of
628 bits in an integer data type.  But you can compute it from the macro
629 @code{CHAR_BIT}, defined in the header file @file{limits.h}.
631 @table @code
632 @comment limits.h
633 @comment ANSI
634 @item CHAR_BIT
635 This is the number of bits in a @code{char}---eight, on most systems.
636 The value has type @code{int}.
638 You can compute the number of bits in any data type @var{type} like
639 this:
641 @smallexample
642 sizeof (@var{type}) * CHAR_BIT
643 @end smallexample
644 @end table
646 @node Range of Type
647 @subsection Range of an Integer Type
648 @cindex integer type range
649 @cindex range of integer type
650 @cindex limits, integer types
652 Suppose you need to store an integer value which can range from zero to
653 one million.  Which is the smallest type you can use?  There is no
654 general rule; it depends on the C compiler and target machine.  You can
655 use the @samp{MIN} and @samp{MAX} macros in @file{limits.h} to determine
656 which type will work.
658 Each signed integer type has a pair of macros which give the smallest
659 and largest values that it can hold.  Each unsigned integer type has one
660 such macro, for the maximum value; the minimum value is, of course,
661 zero.
663 The values of these macros are all integer constant expressions.  The
664 @samp{MAX} and @samp{MIN} macros for @code{char} and @w{@code{short
665 int}} types have values of type @code{int}.  The @samp{MAX} and
666 @samp{MIN} macros for the other types have values of the same type
667 described by the macro---thus, @code{ULONG_MAX} has type
668 @w{@code{unsigned long int}}.
670 @comment Extra blank lines make it look better.
671 @table @code
672 @comment limits.h
673 @comment ANSI
674 @item SCHAR_MIN
676 This is the minimum value that can be represented by a @w{@code{signed char}}.
678 @comment limits.h
679 @comment ANSI
680 @item SCHAR_MAX
681 @comment limits.h
682 @comment ANSI
683 @itemx UCHAR_MAX
685 These are the maximum values that can be represented by a
686 @w{@code{signed char}} and @w{@code{unsigned char}}, respectively.
688 @comment limits.h
689 @comment ANSI
690 @item CHAR_MIN
692 This is the minimum value that can be represented by a @code{char}.
693 It's equal to @code{SCHAR_MIN} if @code{char} is signed, or zero
694 otherwise.
696 @comment limits.h
697 @comment ANSI
698 @item CHAR_MAX
700 This is the maximum value that can be represented by a @code{char}.
701 It's equal to @code{SCHAR_MAX} if @code{char} is signed, or
702 @code{UCHAR_MAX} otherwise.
704 @comment limits.h
705 @comment ANSI
706 @item SHRT_MIN
708 This is the minimum value that can be represented by a @w{@code{signed
709 short int}}.  On most machines that the GNU C library runs on,
710 @code{short} integers are 16-bit quantities.
712 @comment limits.h
713 @comment ANSI
714 @item SHRT_MAX
715 @comment limits.h
716 @comment ANSI
717 @itemx USHRT_MAX
719 These are the maximum values that can be represented by a
720 @w{@code{signed short int}} and @w{@code{unsigned short int}},
721 respectively.
723 @comment limits.h
724 @comment ANSI
725 @item INT_MIN
727 This is the minimum value that can be represented by a @w{@code{signed
728 int}}.  On most machines that the GNU C system runs on, an @code{int} is
729 a 32-bit quantity.
731 @comment limits.h
732 @comment ANSI
733 @item INT_MAX
734 @comment limits.h
735 @comment ANSI
736 @itemx UINT_MAX
738 These are the maximum values that can be represented by, respectively,
739 the type @w{@code{signed int}} and the type @w{@code{unsigned int}}.
741 @comment limits.h
742 @comment ANSI
743 @item LONG_MIN
745 This is the minimum value that can be represented by a @w{@code{signed
746 long int}}.  On most machines that the GNU C system runs on, @code{long}
747 integers are 32-bit quantities, the same size as @code{int}.
749 @comment limits.h
750 @comment ANSI
751 @item LONG_MAX
752 @comment limits.h
753 @comment ANSI
754 @itemx ULONG_MAX
756 These are the maximum values that can be represented by a
757 @w{@code{signed long int}} and @code{unsigned long int}, respectively.
759 @comment limits.h
760 @comment GNU
761 @item LONG_LONG_MIN
763 This is the minimum value that can be represented by a @w{@code{signed
764 long long int}}.  On most machines that the GNU C system runs on,
765 @w{@code{long long}} integers are 64-bit quantities.
767 @comment limits.h
768 @comment GNU
769 @item LONG_LONG_MAX
770 @comment limits.h
771 @comment ANSI
772 @itemx ULONG_LONG_MAX
774 These are the maximum values that can be represented by a @code{signed
775 long long int} and @code{unsigned long long int}, respectively.
777 @comment limits.h
778 @comment GNU
779 @item WCHAR_MAX
781 This is the maximum value that can be represented by a @code{wchar_t}.
782 @xref{Wide Char Intro}.
783 @end table
785 The header file @file{limits.h} also defines some additional constants
786 that parameterize various operating system and file system limits.  These
787 constants are described in @ref{System Configuration}.
789 @node Floating Type Macros
790 @subsection Floating Type Macros
791 @cindex floating type measurements
792 @cindex measurements of floating types
793 @cindex type measurements, floating
794 @cindex limits, floating types
796 The specific representation of floating point numbers varies from
797 machine to machine.  Because floating point numbers are represented
798 internally as approximate quantities, algorithms for manipulating
799 floating point data often need to take account of the precise details of
800 the machine's floating point representation.
802 Some of the functions in the C library itself need this information; for
803 example, the algorithms for printing and reading floating point numbers
804 (@pxref{I/O on Streams}) and for calculating trigonometric and
805 irrational functions (@pxref{Mathematics}) use it to avoid round-off
806 error and loss of accuracy.  User programs that implement numerical
807 analysis techniques also often need this information in order to
808 minimize or compute error bounds.
810 The header file @file{float.h} describes the format used by your
811 machine.
813 @menu
814 * Floating Point Concepts::     Definitions of terminology.
815 * Floating Point Parameters::   Details of specific macros.
816 * IEEE Floating Point::         The measurements for one common
817                                  representation. 
818 @end menu
820 @node Floating Point Concepts
821 @subsubsection Floating Point Representation Concepts
823 This section introduces the terminology for describing floating point
824 representations.
826 You are probably already familiar with most of these concepts in terms
827 of scientific or exponential notation for floating point numbers.  For
828 example, the number @code{123456.0} could be expressed in exponential
829 notation as @code{1.23456e+05}, a shorthand notation indicating that the
830 mantissa @code{1.23456} is multiplied by the base @code{10} raised to
831 power @code{5}.
833 More formally, the internal representation of a floating point number
834 can be characterized in terms of the following parameters:
836 @itemize @bullet
837 @item
838 @cindex sign (of floating point number)
839 The @dfn{sign} is either @code{-1} or @code{1}.
841 @item
842 @cindex base (of floating point number)
843 @cindex radix (of floating point number)
844 The @dfn{base} or @dfn{radix} for exponentiation, an integer greater
845 than @code{1}.  This is a constant for a particular representation.
847 @item
848 @cindex exponent (of floating point number)
849 The @dfn{exponent} to which the base is raised.  The upper and lower
850 bounds of the exponent value are constants for a particular
851 representation.
853 @cindex bias (of floating point number exponent)
854 Sometimes, in the actual bits representing the floating point number,
855 the exponent is @dfn{biased} by adding a constant to it, to make it
856 always be represented as an unsigned quantity.  This is only important
857 if you have some reason to pick apart the bit fields making up the
858 floating point number by hand, which is something for which the GNU
859 library provides no support.  So this is ignored in the discussion that
860 follows.
862 @item
863 @cindex mantissa (of floating point number)
864 @cindex significand (of floating point number)
865 The @dfn{mantissa} or @dfn{significand}, an unsigned integer which is a
866 part of each floating point number.
868 @item 
869 @cindex precision (of floating point number)
870 The @dfn{precision} of the mantissa.  If the base of the representation
871 is @var{b}, then the precision is the number of base-@var{b} digits in
872 the mantissa.  This is a constant for a particular representation.
874 @cindex hidden bit (of floating point number mantissa)
875 Many floating point representations have an implicit @dfn{hidden bit} in
876 the mantissa.  This is a bit which is present virtually in the mantissa,
877 but not stored in memory because its value is always 1 in a normalized
878 number.  The precision figure (see above) includes any hidden bits.
880 Again, the GNU library provides no facilities for dealing with such
881 low-level aspects of the representation.
882 @end itemize
884 The mantissa of a floating point number actually represents an implicit
885 fraction whose denominator is the base raised to the power of the
886 precision.  Since the largest representable mantissa is one less than
887 this denominator, the value of the fraction is always strictly less than
888 @code{1}.  The mathematical value of a floating point number is then the
889 product of this fraction, the sign, and the base raised to the exponent.
891 @cindex normalized floating point number
892 We say that the floating point number is @dfn{normalized} if the
893 fraction is at least @code{1/@var{b}}, where @var{b} is the base.  In
894 other words, the mantissa would be too large to fit if it were
895 multiplied by the base.  Non-normalized numbers are sometimes called
896 @dfn{denormal}; they contain less precision than the representation
897 normally can hold.
899 If the number is not normalized, then you can subtract @code{1} from the
900 exponent while multiplying the mantissa by the base, and get another
901 floating point number with the same value.  @dfn{Normalization} consists
902 of doing this repeatedly until the number is normalized.  Two distinct
903 normalized floating point numbers cannot be equal in value.
905 (There is an exception to this rule: if the mantissa is zero, it is
906 considered normalized.  Another exception happens on certain machines
907 where the exponent is as small as the representation can hold.  Then
908 it is impossible to subtract @code{1} from the exponent, so a number
909 may be normalized even if its fraction is less than @code{1/@var{b}}.)
911 @node Floating Point Parameters
912 @subsubsection Floating Point Parameters
914 @pindex float.h
915 These macro definitions can be accessed by including the header file
916 @file{float.h} in your program.
918 Macro names starting with @samp{FLT_} refer to the @code{float} type,
919 while names beginning with @samp{DBL_} refer to the @code{double} type
920 and names beginning with @samp{LDBL_} refer to the @code{long double}
921 type.  (Currently GCC does not support @code{long double} as a distinct
922 data type, so the values for the @samp{LDBL_} constants are equal to the
923 corresponding constants for the @code{double} type.)@refill
925 Of these macros, only @code{FLT_RADIX} is guaranteed to be a constant
926 expression.  The other macros listed here cannot be reliably used in
927 places that require constant expressions, such as @samp{#if}
928 preprocessing directives or in the dimensions of static arrays.
930 Although the ANSI C standard specifies minimum and maximum values for
931 most of these parameters, the GNU C implementation uses whatever values
932 describe the floating point representation of the target machine.  So in
933 principle GNU C actually satisfies the ANSI C requirements only if the
934 target machine is suitable.  In practice, all the machines currently
935 supported are suitable.
937 @table @code
938 @comment float.h
939 @comment ANSI
940 @item FLT_ROUNDS
941 This value characterizes the rounding mode for floating point addition.
942 The following values indicate standard rounding modes:
944 @need 750
946 @table @code
947 @item -1
948 The mode is indeterminable.
949 @item 0
950 Rounding is towards zero.
951 @item 1
952 Rounding is to the nearest number.
953 @item 2
954 Rounding is towards positive infinity.
955 @item 3
956 Rounding is towards negative infinity.
957 @end table
959 @noindent
960 Any other value represents a machine-dependent nonstandard rounding
961 mode.
963 On most machines, the value is @code{1}, in accordance with the IEEE
964 standard for floating point.
966 Here is a table showing how certain values round for each possible value
967 of @code{FLT_ROUNDS}, if the other aspects of the representation match
968 the IEEE single-precision standard.
970 @smallexample
971                 0      1             2             3
972  1.00000003    1.0    1.0           1.00000012    1.0
973  1.00000007    1.0    1.00000012    1.00000012    1.0
974 -1.00000003   -1.0   -1.0          -1.0          -1.00000012
975 -1.00000007   -1.0   -1.00000012   -1.0          -1.00000012
976 @end smallexample
978 @comment float.h
979 @comment ANSI
980 @item FLT_RADIX
981 This is the value of the base, or radix, of exponent representation.
982 This is guaranteed to be a constant expression, unlike the other macros
983 described in this section.  The value is 2 on all machines we know of
984 except the IBM 360 and derivatives.
986 @comment float.h
987 @comment ANSI
988 @item FLT_MANT_DIG
989 This is the number of base-@code{FLT_RADIX} digits in the floating point
990 mantissa for the @code{float} data type.  The following expression
991 yields @code{1.0} (even though mathematically it should not) due to the
992 limited number of mantissa digits:
994 @smallexample
995 float radix = FLT_RADIX;
997 1.0f + 1.0f / radix / radix / @dots{} / radix
998 @end smallexample
1000 @noindent
1001 where @code{radix} appears @code{FLT_MANT_DIG} times.
1003 @comment float.h
1004 @comment ANSI
1005 @item DBL_MANT_DIG
1006 @itemx LDBL_MANT_DIG
1007 This is the number of base-@code{FLT_RADIX} digits in the floating point
1008 mantissa for the data types @code{double} and @code{long double},
1009 respectively.
1011 @comment Extra blank lines make it look better.
1012 @comment float.h
1013 @comment ANSI
1014 @item FLT_DIG
1016 This is the number of decimal digits of precision for the @code{float}
1017 data type.  Technically, if @var{p} and @var{b} are the precision and
1018 base (respectively) for the representation, then the decimal precision
1019 @var{q} is the maximum number of decimal digits such that any floating
1020 point number with @var{q} base 10 digits can be rounded to a floating
1021 point number with @var{p} base @var{b} digits and back again, without
1022 change to the @var{q} decimal digits.
1024 The value of this macro is supposed to be at least @code{6}, to satisfy
1025 ANSI C.
1027 @comment float.h
1028 @comment ANSI
1029 @item DBL_DIG
1030 @itemx LDBL_DIG
1032 These are similar to @code{FLT_DIG}, but for the data types
1033 @code{double} and @code{long double}, respectively.  The values of these
1034 macros are supposed to be at least @code{10}.
1036 @comment float.h
1037 @comment ANSI
1038 @item FLT_MIN_EXP
1039 This is the smallest possible exponent value for type @code{float}.
1040 More precisely, is the minimum negative integer such that the value
1041 @code{FLT_RADIX} raised to this power minus 1 can be represented as a
1042 normalized floating point number of type @code{float}.
1044 @comment float.h
1045 @comment ANSI
1046 @item DBL_MIN_EXP
1047 @itemx LDBL_MIN_EXP
1049 These are similar to @code{FLT_MIN_EXP}, but for the data types
1050 @code{double} and @code{long double}, respectively.
1052 @comment float.h
1053 @comment ANSI
1054 @item FLT_MIN_10_EXP
1055 This is the minimum negative integer such that @code{10} raised to this
1056 power minus 1 can be represented as a normalized floating point number
1057 of type @code{float}.  This is supposed to be @code{-37} or even less.
1059 @comment float.h
1060 @comment ANSI
1061 @item DBL_MIN_10_EXP
1062 @itemx LDBL_MIN_10_EXP
1063 These are similar to @code{FLT_MIN_10_EXP}, but for the data types
1064 @code{double} and @code{long double}, respectively.
1066 @comment float.h
1067 @comment ANSI
1068 @item FLT_MAX_EXP
1069 This is the largest possible exponent value for type @code{float}.  More
1070 precisely, this is the maximum positive integer such that value
1071 @code{FLT_RADIX} raised to this power minus 1 can be represented as a
1072 floating point number of type @code{float}.
1074 @comment float.h
1075 @comment ANSI
1076 @item DBL_MAX_EXP
1077 @itemx LDBL_MAX_EXP
1078 These are similar to @code{FLT_MAX_EXP}, but for the data types
1079 @code{double} and @code{long double}, respectively.
1081 @comment float.h
1082 @comment ANSI
1083 @item FLT_MAX_10_EXP
1084 This is the maximum positive integer such that @code{10} raised to this
1085 power minus 1 can be represented as a normalized floating point number
1086 of type @code{float}.  This is supposed to be at least @code{37}.
1088 @comment float.h
1089 @comment ANSI
1090 @item DBL_MAX_10_EXP
1091 @itemx LDBL_MAX_10_EXP
1092 These are similar to @code{FLT_MAX_10_EXP}, but for the data types
1093 @code{double} and @code{long double}, respectively.
1095 @comment float.h
1096 @comment ANSI
1097 @item FLT_MAX
1099 The value of this macro is the maximum number representable in type
1100 @code{float}.  It is supposed to be at least @code{1E+37}.  The value
1101 has type @code{float}.
1103 The smallest representable number is @code{- FLT_MAX}.
1105 @comment float.h
1106 @comment ANSI
1107 @item DBL_MAX
1108 @itemx LDBL_MAX
1110 These are similar to @code{FLT_MAX}, but for the data types
1111 @code{double} and @code{long double}, respectively.  The type of the
1112 macro's value is the same as the type it describes.
1114 @comment float.h
1115 @comment ANSI
1116 @item FLT_MIN
1118 The value of this macro is the minimum normalized positive floating
1119 point number that is representable in type @code{float}.  It is supposed
1120 to be no more than @code{1E-37}.
1122 @comment float.h
1123 @comment ANSI
1124 @item DBL_MIN
1125 @itemx LDBL_MIN
1127 These are similar to @code{FLT_MIN}, but for the data types
1128 @code{double} and @code{long double}, respectively.  The type of the
1129 macro's value is the same as the type it describes.
1131 @comment float.h
1132 @comment ANSI
1133 @item FLT_EPSILON
1135 This is the minimum positive floating point number of type @code{float}
1136 such that @code{1.0 + FLT_EPSILON != 1.0} is true.  It's supposed to
1137 be no greater than @code{1E-5}.
1139 @comment float.h
1140 @comment ANSI
1141 @item DBL_EPSILON
1142 @itemx LDBL_EPSILON
1144 These are similar to @code{FLT_EPSILON}, but for the data types
1145 @code{double} and @code{long double}, respectively.  The type of the
1146 macro's value is the same as the type it describes.  The values are not
1147 supposed to be greater than @code{1E-9}.
1148 @end table
1150 @node IEEE Floating Point
1151 @subsubsection IEEE Floating Point
1152 @cindex IEEE floating point representation 
1153 @cindex floating point, IEEE
1155 Here is an example showing how the floating type measurements come out
1156 for the most common floating point representation, specified by the
1157 @cite{IEEE Standard for Binary Floating Point Arithmetic (ANSI/IEEE Std
1158 754-1985)}.  Nearly all computers designed since the 1980s use this
1159 format.
1161 The IEEE single-precision float representation uses a base of 2.  There
1162 is a sign bit, a mantissa with 23 bits plus one hidden bit (so the total
1163 precision is 24 base-2 digits), and an 8-bit exponent that can represent
1164 values in the range -125 to 128, inclusive.
1166 So, for an implementation that uses this representation for the
1167 @code{float} data type, appropriate values for the corresponding
1168 parameters are:
1170 @smallexample
1171 FLT_RADIX                             2
1172 FLT_MANT_DIG                         24
1173 FLT_DIG                               6
1174 FLT_MIN_EXP                        -125
1175 FLT_MIN_10_EXP                      -37
1176 FLT_MAX_EXP                         128
1177 FLT_MAX_10_EXP                      +38
1178 FLT_MIN                 1.17549435E-38F
1179 FLT_MAX                 3.40282347E+38F
1180 FLT_EPSILON             1.19209290E-07F
1181 @end smallexample
1183 Here are the values for the @code{double} data type:
1185 @smallexample
1186 DBL_MANT_DIG                         53
1187 DBL_DIG                              15
1188 DBL_MIN_EXP                       -1021
1189 DBL_MIN_10_EXP                     -307
1190 DBL_MAX_EXP                        1024
1191 DBL_MAX_10_EXP                      308
1192 DBL_MAX         1.7976931348623157E+308
1193 DBL_MIN         2.2250738585072014E-308
1194 DBL_EPSILON     2.2204460492503131E-016
1195 @end smallexample
1197 @node Structure Measurement
1198 @subsection Structure Field Offset Measurement
1200 You can use @code{offsetof} to measure the location within a structure
1201 type of a particular structure member.
1203 @comment stddef.h
1204 @comment ANSI
1205 @deftypefn {Macro} size_t offsetof (@var{type}, @var{member})
1206 This expands to a integer constant expression that is the offset of the
1207 structure member named @var{member} in a the structure type @var{type}.
1208 For example, @code{offsetof (struct s, elem)} is the offset, in bytes,
1209 of the member @code{elem} in a @code{struct s}.
1211 This macro won't work if @var{member} is a bit field; you get an error
1212 from the C compiler in that case.
1213 @end deftypefn