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