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