1 @node Arithmetic, Date and Time, Mathematics, Top
2 @chapter Low-Level Arithmetic Functions
4 This chapter contains information about functions for doing basic
5 arithmetic operations, such as splitting a float into its integer and
6 fractional parts or retrieving the imaginary part of a complex value.
7 These functions are declared in the header files @file{math.h} and
11 * Infinity:: What is Infinity and how to test for it.
12 * Not a Number:: Making NaNs and testing for NaNs.
13 * Imaginary Unit:: Constructing complex Numbers.
14 * Predicates on Floats:: Testing for infinity and for NaNs.
15 * Floating-Point Classes:: Classifiy floating-point numbers.
16 * Operations on Complex:: Projections, Conjugates, and Decomposing.
17 * Absolute Value:: Absolute value functions.
18 * Normalization Functions:: Hacks for radix-2 representations.
19 * Rounding and Remainders:: Determining the integer and
20 fractional parts of a float.
21 * Integer Division:: Functions for performing integer
23 * Parsing of Numbers:: Functions for ``reading'' numbers
28 @section Infinity Values
30 @cindex IEEE floating point
32 Mathematical operations easily can produce as the result values which
33 are not representable by the floating-point format. The functions in
34 the mathematics library also have this problem. The situation is
35 generally solved by raising an overflow exception and by returning a
38 The @w{IEEE 754} floating-point defines a special value to be used in
39 these situations. There is a special value for infinity.
43 @deftypevr Macro float_t INFINITY
44 A expression representing the inifite value. @code{INFINITY} values are
45 produce by mathematical operations like @code{1.0 / 0.0}. It is
46 possible to continue the computations with this value since the basic
47 operations as well as the mathematical library functions are prepared to
48 handle values like this.
50 Beside @code{INFINITY} also the value @code{-INIFITY} is representable
51 and it is handled differently if needed. It is possible to test a
52 variables for infinite value using a simple comparison but the
53 recommended way is to use the the @code{isinf} function.
55 This macro was introduced in the @w{ISO C 9X} standard.
59 The macros @code{HUGE_VAL}, @code{HUGE_VALF} and @code{HUGE_VALL} are
60 defined in a similar way but they are not required to represent the
61 infinite value, only a very large value (@pxref{Domain and Range Errors}).
62 If actually infinity is wanted, @code{INFINITY} should be used.
66 @section ``Not a Number'' Values
69 @cindex IEEE floating point
71 The IEEE floating point format used by most modern computers supports
72 values that are ``not a number''. These values are called @dfn{NaNs}.
73 ``Not a number'' values result from certain operations which have no
74 meaningful numeric result, such as zero divided by zero or infinity
77 One noteworthy property of NaNs is that they are not equal to
78 themselves. Thus, @code{x == x} can be 0 if the value of @code{x} is a
79 NaN. You can use this to test whether a value is a NaN or not: if it is
80 not equal to itself, then it is a NaN. But the recommended way to test
81 for a NaN is with the @code{isnan} function (@pxref{Predicates on Floats}).
83 Almost any arithmetic operation in which one argument is a NaN returns
88 @deftypevr Macro double NAN
89 An expression representing a value which is ``not a number''. This
90 macro is a GNU extension, available only on machines that support ``not
91 a number'' values---that is to say, on all machines that support IEEE
94 You can use @samp{#ifdef NAN} to test whether the machine supports
95 NaNs. (Of course, you must arrange for GNU extensions to be visible,
96 such as by defining @code{_GNU_SOURCE}, and then you must include
101 @section Constructing complex Numbers
104 To construct complex numbers it is necessary have a way to express the
105 imaginary part of the numbers. In mathematics one uses the symbol ``i''
106 to mark a number as imaginary. For convenienve the @file{complex.h}
107 header defines two macros which allow to use a similar easy notation.
109 @deftypevr Macro float_t _Imaginary_I
110 This macro is a (compiler specific) representation of the value ``1i''.
111 I.e., it is the value for which
114 _Imaginary_I * _Imaginary_I = -1
118 One can use it to easily construct complex number like in
121 3.0 - _Imaginary_I * 4.0
125 which results in the complex number with a real part of 3.0 and a
130 A more intuitive approach is to use the following macro.
132 @deftypevr Macro float_t I
133 This macro has exactly the same value as @code{_Imaginary_I}. The
134 problem is that the name @code{I} very easily can clash with macros or
135 variables in programs and so it might be a good idea to avoid this name
136 and stay at the safe side by using @code{_Imaginary_I}.
140 @node Predicates on Floats
141 @section Predicates on Floats
144 This section describes some miscellaneous test functions on doubles.
145 Prototypes for these functions appear in @file{math.h}. These are BSD
146 functions, and thus are available if you define @code{_BSD_SOURCE} or
151 @deftypefun int isinf (double @var{x})
152 @deftypefunx int isinff (float @var{x})
153 @deftypefunx int isinfl (long double @var{x})
154 This function returns @code{-1} if @var{x} represents negative infinity,
155 @code{1} if @var{x} represents positive infinity, and @code{0} otherwise.
160 @deftypefun int isnan (double @var{x})
161 @deftypefunx int isnanf (float @var{x})
162 @deftypefunx int isnanl (long double @var{x})
163 This function returns a nonzero value if @var{x} is a ``not a number''
164 value, and zero otherwise. (You can just as well use @code{@var{x} !=
165 @var{x}} to get the same result).
170 @deftypefun int finite (double @var{x})
171 @deftypefunx int finitef (float @var{x})
172 @deftypefunx int finitel (long double @var{x})
173 This function returns a nonzero value if @var{x} is finite or a ``not a
174 number'' value, and zero otherwise.
179 @deftypefun double infnan (int @var{error})
180 This function is provided for compatibility with BSD. The other
181 mathematical functions use @code{infnan} to decide what to return on
182 occasion of an error. Its argument is an error code, @code{EDOM} or
183 @code{ERANGE}; @code{infnan} returns a suitable value to indicate this
184 with. @code{-ERANGE} is also acceptable as an argument, and corresponds
185 to @code{-HUGE_VAL} as a value.
187 In the BSD library, on certain machines, @code{infnan} raises a fatal
188 signal in all cases. The GNU library does not do likewise, because that
189 does not fit the @w{ISO C} specification.
192 @strong{Portability Note:} The functions listed in this section are BSD
195 @node Floating-Point Classes
196 @section Floating-Point Number Classification Functions
198 Instead of using the BSD specific functions from the last section it is
199 better to use those in this section which are introduced in the @w{ISO C
200 9X} standard and are therefore widely available.
204 @deftypefun int fpclassify (@emph{float-type} @var{x})
205 This is a generic macro which works on all floating-point types and
206 which returns a value of type @code{int}. The possible values are:
210 The floating-point number @var{x} is ``Not a Number'' (@pxref{Not a Number})
212 The value of @var{x} is either plus or minus infinity (@pxref{Infinity})
214 The value of @var{x} is zero. In floating-point formats like @w{IEEE
215 754} where the zero value can be signed this value is also returned if
216 @var{x} is minus zero.
218 Some floating-point formats (such as @w{IEEE 754}) allow floating-point
219 numbers to be represented in a denormalized format. This happens if the
220 absolute value of the number is too small to be represented in the
221 normal format. @code{FP_SUBNORMAL} is returned for such values of @var{x}.
223 This value is returned for all other cases which means the number is a
224 plain floating-point number without special meaning.
227 This macro is useful if more than property of a number must be
228 tested. If one only has to test for, e.g., a NaN value, there are
229 function which are faster.
232 The remainder of this section introduces some more specific functions.
233 They might be implemented faster than the call to @code{fpclassify} and
234 if the actual need in the program is covered be these functions they
235 should be used (and not @code{fpclassify}).
239 @deftypefun int isfinite (@emph{float-type} @var{x})
240 The value returned by this macro is nonzero if the value of @var{x} is
241 not plus or minus infinity and not NaN. I.e., it could be implemented as
244 (fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE)
247 @code{isfinite} is also implemented as a macro which can handle all
248 floating-point types. Programs should use this function instead of
249 @var{finite} (@pxref{Predicates on Floats}).
254 @deftypefun int isnormal (@emph{float-type} @var{x})
255 If @code{isnormal} returns a nonzero value the value or @var{x} is
256 neither a NaN, infinity, zero, nor a denormalized number. I.e., it
257 could be implemented as
260 (fpclassify (x) == FP_NORMAL)
266 @deftypefun int isnan (@emph{float-type} @var{x})
267 The situation with this macro is a bit complicated. Here @code{isnan}
268 is a macro which can handle all kinds of floating-point types. It
269 returns a nonzero value is @var{x} does not represent a NaN value and
270 could be written like this
273 (fpclassify (x) == FP_NAN)
276 The complication is that there is a function of the same name and the
277 same semantic defined for compatibility with BSD (@pxref{Predicates on
278 Floats}). Fortunately this should not yield to problems in most cases
279 since the macro and the function have the same semantic. Should in a
280 situation the function be absolutely necessary one can use
287 to avoid the macro expansion. Using the macro has two big adavantages:
288 it is more portable and one does not have to choose the right function
289 among @code{isnan}, @code{isnanf}, and @code{isnanl}.
293 @node Operations on Complex
294 @section Projections, Conjugates, and Decomposing of Complex Numbers
295 @cindex project complex numbers
296 @cindex conjugate complex numbers
297 @cindex decompose complex numbers
299 This section lists functions performing some of the simple mathematical
300 operations on complex numbers. Using any of the function requries that
301 the C compiler understands the @code{complex} keyword, introduced to the
302 C language in the @w{ISO C 9X} standard.
305 The prototypes for all functions in this section can be found in
306 @file{complex.h}. All functions are available in three variants, one
307 for each of the three floating-point types.
309 The easiest operation on complex numbers is the decomposition in the
310 real part and the imaginary part. This is done by the next two
315 @deftypefun double creal (complex double @var{z})
316 @deftypefunx float crealf (complex float @var{z})
317 @deftypefunx {long double} creall (complex long double @var{z})
318 These functions return the real part of the complex number @var{z}.
323 @deftypefun double cimag (complex double @var{z})
324 @deftypefunx float cimagf (complex float @var{z})
325 @deftypefunx {long double} cimagl (complex long double @var{z})
326 These functions return the imaginary part of the complex number @var{z}.
330 The conjugate complex value of a given complex number has the same value
331 for the real part but the complex part is negated.
335 @deftypefun {complex double} conj (complex double @var{z})
336 @deftypefunx {complex float} conjf (complex float @var{z})
337 @deftypefunx {complex long double} conjl (complex long double @var{z})
338 These functions return the conjugate complex value of the complex number
344 @deftypefun double carg (complex double @var{z})
345 @deftypefunx float cargf (complex float @var{z})
346 @deftypefunx {long double} cargl (complex long double @var{z})
347 These functions return argument of the complex number @var{z}.
349 Mathematically, the argument is the phase angle of @var{z} with a branch
350 cut along the negative real axis.
355 @deftypefun {complex double} cproj (complex double @var{z})
356 @deftypefunx {complex float} cprojf (complex float @var{z})
357 @deftypefunx {complex long double} cprojl (complex long double @var{z})
358 Return the projection of the complex value @var{z} on the Riemann
359 sphere. Values with a infinite complex part (even if the real part
360 is NaN) are projected to positive infinte on the real axis. If the real part is infinite, the result is equivalent to
363 INFINITY + I * copysign (0.0, cimag (z))
369 @section Absolute Value
370 @cindex absolute value functions
372 These functions are provided for obtaining the @dfn{absolute value} (or
373 @dfn{magnitude}) of a number. The absolute value of a real number
374 @var{x} is @var{x} is @var{x} is positive, @minus{}@var{x} if @var{x} is
375 negative. For a complex number @var{z}, whose real part is @var{x} and
376 whose imaginary part is @var{y}, the absolute value is @w{@code{sqrt
377 (@var{x}*@var{x} + @var{y}*@var{y})}}.
381 Prototypes for @code{abs} and @code{labs} are in @file{stdlib.h};
382 @code{fabs}, @code{fabsf} and @code{fabsl} are declared in @file{math.h};
383 @code{cabs}, @code{cabsf} and @code{cabsl} are declared in @file{complex.h}.
387 @deftypefun int abs (int @var{number})
388 This function returns the absolute value of @var{number}.
390 Most computers use a two's complement integer representation, in which
391 the absolute value of @code{INT_MIN} (the smallest possible @code{int})
392 cannot be represented; thus, @w{@code{abs (INT_MIN)}} is not defined.
397 @deftypefun {long int} labs (long int @var{number})
398 This is similar to @code{abs}, except that both the argument and result
399 are of type @code{long int} rather than @code{int}.
404 @deftypefun double fabs (double @var{number})
405 @deftypefunx float fabsf (float @var{number})
406 @deftypefunx {long double} fabsl (long double @var{number})
407 This function returns the absolute value of the floating-point number
413 @deftypefun double cabs (complex double @var{z})
414 @deftypefunx float cabsf (complex float @var{z})
415 @deftypefunx {long double} cabsl (complex long double @var{z})
416 These functions return the absolute value of the complex number @var{z}.
417 The compiler must support complex numbers to use these functions. (See
418 also the function @code{hypot} in @ref{Exponents and Logarithms}.) The
422 sqrt (creal (@var{z}) * creal (@var{z}) + cimag (@var{z}) * cimag (@var{z}))
426 @node Normalization Functions
427 @section Normalization Functions
428 @cindex normalization functions (floating-point)
430 The functions described in this section are primarily provided as a way
431 to efficiently perform certain low-level manipulations on floating point
432 numbers that are represented internally using a binary radix;
433 see @ref{Floating Point Concepts}. These functions are required to
434 have equivalent behavior even if the representation does not use a radix
435 of 2, but of course they are unlikely to be particularly efficient in
439 All these functions are declared in @file{math.h}.
443 @deftypefun double frexp (double @var{value}, int *@var{exponent})
444 @deftypefunx float frexpf (float @var{value}, int *@var{exponent})
445 @deftypefunx {long double} frexpl (long double @var{value}, int *@var{exponent})
446 These functions are used to split the number @var{value}
447 into a normalized fraction and an exponent.
449 If the argument @var{value} is not zero, the return value is @var{value}
450 times a power of two, and is always in the range 1/2 (inclusive) to 1
451 (exclusive). The corresponding exponent is stored in
452 @code{*@var{exponent}}; the return value multiplied by 2 raised to this
453 exponent equals the original number @var{value}.
455 For example, @code{frexp (12.8, &exponent)} returns @code{0.8} and
456 stores @code{4} in @code{exponent}.
458 If @var{value} is zero, then the return value is zero and
459 zero is stored in @code{*@var{exponent}}.
464 @deftypefun double ldexp (double @var{value}, int @var{exponent})
465 @deftypefunx float ldexpf (float @var{value}, int @var{exponent})
466 @deftypefunx {long double} ldexpl (long double @var{value}, int @var{exponent})
467 These functions return the result of multiplying the floating-point
468 number @var{value} by 2 raised to the power @var{exponent}. (It can
469 be used to reassemble floating-point numbers that were taken apart
472 For example, @code{ldexp (0.8, 4)} returns @code{12.8}.
475 The following functions which come from BSD provide facilities
476 equivalent to those of @code{ldexp} and @code{frexp}:
480 @deftypefun double scalb (double @var{value}, int @var{exponent})
481 @deftypefunx float scalbf (float @var{value}, int @var{exponent})
482 @deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent})
483 The @code{scalb} function is the BSD name for @code{ldexp}.
488 @deftypefun double logb (double @var{x})
489 @deftypefunx float logbf (float @var{x})
490 @deftypefunx {long double} logbl (long double @var{x})
491 These BSD functions return the integer part of the base-2 logarithm of
492 @var{x}, an integer value represented in type @code{double}. This is
493 the highest integer power of @code{2} contained in @var{x}. The sign of
494 @var{x} is ignored. For example, @code{logb (3.5)} is @code{1.0} and
495 @code{logb (4.0)} is @code{2.0}.
497 When @code{2} raised to this power is divided into @var{x}, it gives a
498 quotient between @code{1} (inclusive) and @code{2} (exclusive).
500 If @var{x} is zero, the value is minus infinity (if the machine supports
501 such a value), or else a very small number. If @var{x} is infinity, the
504 The value returned by @code{logb} is one less than the value that
505 @code{frexp} would store into @code{*@var{exponent}}.
510 @deftypefun double copysign (double @var{value}, double @var{sign})
511 @deftypefunx float copysignf (float @var{value}, float @var{sign})
512 @deftypefunx {long double} copysignl (long double @var{value}, long double @var{sign})
513 These functions return a value whose absolute value is the
514 same as that of @var{value}, and whose sign matches that of @var{sign}.
515 This function appears in BSD and was standardized in @w{ISO C 9X}.
520 @deftypefun int signbit (@emph{float-type} @var{x})
521 @code{signbit} is a generic macro which can work on all floating-point
522 types. It returns a nonzero value if the value of @var{x} has its sign
525 This is not the same as @code{x < 0.0} since in some floating-point
526 formats (e.g., @w{IEEE 754}) the zero value is optionally signed. The
527 comparison @code{-0.0 < 0.0} will not be true while @code{signbit
528 (-0.0)} will return a nonzeri value.
531 @node Rounding and Remainders
532 @section Rounding and Remainder Functions
533 @cindex rounding functions
534 @cindex remainder functions
535 @cindex converting floats to integers
538 The functions listed here perform operations such as rounding,
539 truncation, and remainder in division of floating point numbers. Some
540 of these functions convert floating point numbers to integer values.
541 They are all declared in @file{math.h}.
543 You can also convert floating-point numbers to integers simply by
544 casting them to @code{int}. This discards the fractional part,
545 effectively rounding towards zero. However, this only works if the
546 result can actually be represented as an @code{int}---for very large
547 numbers, this is impossible. The functions listed here return the
548 result as a @code{double} instead to get around this problem.
552 @deftypefun double ceil (double @var{x})
553 @deftypefunx float ceilf (float @var{x})
554 @deftypefunx {long double} ceill (long double @var{x})
555 These functions round @var{x} upwards to the nearest integer,
556 returning that value as a @code{double}. Thus, @code{ceil (1.5)}
562 @deftypefun double floor (double @var{x})
563 @deftypefunx float floorf (float @var{x})
564 @deftypefunx {long double} floorl (long double @var{x})
565 These functions round @var{x} downwards to the nearest
566 integer, returning that value as a @code{double}. Thus, @code{floor
567 (1.5)} is @code{1.0} and @code{floor (-1.5)} is @code{-2.0}.
572 @deftypefun double rint (double @var{x})
573 @deftypefunx float rintf (float @var{x})
574 @deftypefunx {long double} rintl (long double @var{x})
575 These functions round @var{x} to an integer value according to the
576 current rounding mode. @xref{Floating Point Parameters}, for
577 information about the various rounding modes. The default
578 rounding mode is to round to the nearest integer; some machines
579 support other modes, but round-to-nearest is always used unless
580 you explicit select another.
585 @deftypefun double nearbyint (double @var{x})
586 @deftypefunx float nearbyintf (float @var{x})
587 @deftypefunx {long double} nearbyintl (long double @var{x})
588 These functions return the same value as the @code{rint} functions but
589 even some rounding actually takes place @code{nearbyint} does @emph{not}
590 raise the inexact exception.
595 @deftypefun double modf (double @var{value}, double *@var{integer-part})
596 @deftypefunx float modff (flaot @var{value}, float *@var{integer-part})
597 @deftypefunx {long double} modfl (long double @var{value}, long double *@var{integer-part})
598 These functions break the argument @var{value} into an integer part and a
599 fractional part (between @code{-1} and @code{1}, exclusive). Their sum
600 equals @var{value}. Each of the parts has the same sign as @var{value},
601 so the rounding of the integer part is towards zero.
603 @code{modf} stores the integer part in @code{*@var{integer-part}}, and
604 returns the fractional part. For example, @code{modf (2.5, &intpart)}
605 returns @code{0.5} and stores @code{2.0} into @code{intpart}.
610 @deftypefun double fmod (double @var{numerator}, double @var{denominator})
611 @deftypefunx float fmodf (float @var{numerator}, float @var{denominator})
612 @deftypefunx {long double} fmodl (long double @var{numerator}, long double @var{denominator})
613 These functions compute the remainder from the division of
614 @var{numerator} by @var{denominator}. Specifically, the return value is
615 @code{@var{numerator} - @w{@var{n} * @var{denominator}}}, where @var{n}
616 is the quotient of @var{numerator} divided by @var{denominator}, rounded
617 towards zero to an integer. Thus, @w{@code{fmod (6.5, 2.3)}} returns
618 @code{1.9}, which is @code{6.5} minus @code{4.6}.
620 The result has the same sign as the @var{numerator} and has magnitude
621 less than the magnitude of the @var{denominator}.
623 If @var{denominator} is zero, @code{fmod} fails and sets @code{errno} to
629 @deftypefun double drem (double @var{numerator}, double @var{denominator})
630 @deftypefunx float dremf (float @var{numerator}, float @var{denominator})
631 @deftypefunx {long double} dreml (long double @var{numerator}, long double @var{denominator})
632 These functions are like @code{fmod} etc except that it rounds the
633 internal quotient @var{n} to the nearest integer instead of towards zero
634 to an integer. For example, @code{drem (6.5, 2.3)} returns @code{-0.4},
635 which is @code{6.5} minus @code{6.9}.
637 The absolute value of the result is less than or equal to half the
638 absolute value of the @var{denominator}. The difference between
639 @code{fmod (@var{numerator}, @var{denominator})} and @code{drem
640 (@var{numerator}, @var{denominator})} is always either
641 @var{denominator}, minus @var{denominator}, or zero.
643 If @var{denominator} is zero, @code{drem} fails and sets @code{errno} to
648 @node Integer Division
649 @section Integer Division
650 @cindex integer division functions
652 This section describes functions for performing integer division. These
653 functions are redundant in the GNU C library, since in GNU C the @samp{/}
654 operator always rounds towards zero. But in other C implementations,
655 @samp{/} may round differently with negative arguments. @code{div} and
656 @code{ldiv} are useful because they specify how to round the quotient:
657 towards zero. The remainder has the same sign as the numerator.
659 These functions are specified to return a result @var{r} such that the value
660 @code{@var{r}.quot*@var{denominator} + @var{r}.rem} equals
664 To use these facilities, you should include the header file
665 @file{stdlib.h} in your program.
669 @deftp {Data Type} div_t
670 This is a structure type used to hold the result returned by the @code{div}
671 function. It has the following members:
675 The quotient from the division.
678 The remainder from the division.
684 @deftypefun div_t div (int @var{numerator}, int @var{denominator})
685 This function @code{div} computes the quotient and remainder from
686 the division of @var{numerator} by @var{denominator}, returning the
687 result in a structure of type @code{div_t}.
689 If the result cannot be represented (as in a division by zero), the
690 behavior is undefined.
692 Here is an example, albeit not a very useful one.
696 result = div (20, -6);
700 Now @code{result.quot} is @code{-3} and @code{result.rem} is @code{2}.
705 @deftp {Data Type} ldiv_t
706 This is a structure type used to hold the result returned by the @code{ldiv}
707 function. It has the following members:
711 The quotient from the division.
714 The remainder from the division.
717 (This is identical to @code{div_t} except that the components are of
718 type @code{long int} rather than @code{int}.)
723 @deftypefun ldiv_t ldiv (long int @var{numerator}, long int @var{denominator})
724 The @code{ldiv} function is similar to @code{div}, except that the
725 arguments are of type @code{long int} and the result is returned as a
726 structure of type @code{ldiv_t}.
731 @deftp {Data Type} lldiv_t
732 This is a structure type used to hold the result returned by the @code{lldiv}
733 function. It has the following members:
736 @item long long int quot
737 The quotient from the division.
739 @item long long int rem
740 The remainder from the division.
743 (This is identical to @code{div_t} except that the components are of
744 type @code{long long int} rather than @code{int}.)
749 @deftypefun lldiv_t lldiv (long long int @var{numerator}, long long int @var{denominator})
750 The @code{lldiv} function is like the @code{div} function, but the
751 arguments are of type @code{long long int} and the result is returned as
752 a structure of type @code{lldiv_t}.
754 The @code{lldiv} function is a GNU extension but it will eventually be
755 part of the next ISO C standard.
759 @node Parsing of Numbers
760 @section Parsing of Numbers
761 @cindex parsing numbers (in formatted input)
762 @cindex converting strings to numbers
763 @cindex number syntax, parsing
764 @cindex syntax, for reading numbers
766 This section describes functions for ``reading'' integer and
767 floating-point numbers from a string. It may be more convenient in some
768 cases to use @code{sscanf} or one of the related functions; see
769 @ref{Formatted Input}. But often you can make a program more robust by
770 finding the tokens in the string by hand, then converting the numbers
774 * Parsing of Integers:: Functions for conversion of integer values.
775 * Parsing of Floats:: Functions for conversion of floating-point
779 @node Parsing of Integers
780 @subsection Parsing of Integers
783 These functions are declared in @file{stdlib.h}.
787 @deftypefun {long int} strtol (const char *@var{string}, char **@var{tailptr}, int @var{base})
788 The @code{strtol} (``string-to-long'') function converts the initial
789 part of @var{string} to a signed integer, which is returned as a value
790 of type @code{long int}.
792 This function attempts to decompose @var{string} as follows:
796 A (possibly empty) sequence of whitespace characters. Which characters
797 are whitespace is determined by the @code{isspace} function
798 (@pxref{Classification of Characters}). These are discarded.
801 An optional plus or minus sign (@samp{+} or @samp{-}).
804 A nonempty sequence of digits in the radix specified by @var{base}.
806 If @var{base} is zero, decimal radix is assumed unless the series of
807 digits begins with @samp{0} (specifying octal radix), or @samp{0x} or
808 @samp{0X} (specifying hexadecimal radix); in other words, the same
809 syntax used for integer constants in C.
811 Otherwise @var{base} must have a value between @code{2} and @code{35}.
812 If @var{base} is @code{16}, the digits may optionally be preceded by
813 @samp{0x} or @samp{0X}. If base has no legal value the value returned
814 is @code{0l} and the global variable @code{errno} is set to @code{EINVAL}.
817 Any remaining characters in the string. If @var{tailptr} is not a null
818 pointer, @code{strtol} stores a pointer to this tail in
819 @code{*@var{tailptr}}.
822 If the string is empty, contains only whitespace, or does not contain an
823 initial substring that has the expected syntax for an integer in the
824 specified @var{base}, no conversion is performed. In this case,
825 @code{strtol} returns a value of zero and the value stored in
826 @code{*@var{tailptr}} is the value of @var{string}.
828 In a locale other than the standard @code{"C"} locale, this function
829 may recognize additional implementation-dependent syntax.
831 If the string has valid syntax for an integer but the value is not
832 representable because of overflow, @code{strtol} returns either
833 @code{LONG_MAX} or @code{LONG_MIN} (@pxref{Range of Type}), as
834 appropriate for the sign of the value. It also sets @code{errno}
835 to @code{ERANGE} to indicate there was overflow.
837 Because the value @code{0l} is a correct result for @code{strtol} the
838 user who is interested in handling errors should set the global variable
839 @code{errno} to @code{0} before calling this function, so that the program
840 can later test whether an error occurred.
842 There is an example at the end of this section.
847 @deftypefun {unsigned long int} strtoul (const char *@var{string}, char **@var{tailptr}, int @var{base})
848 The @code{strtoul} (``string-to-unsigned-long'') function is like
849 @code{strtol} except it deals with unsigned numbers, and returns its
850 value with type @code{unsigned long int}. No @samp{+} or @samp{-} sign
851 may appear before the number, but the syntax is otherwise the same as
852 described above for @code{strtol}. The value returned in case of
853 overflow is @code{ULONG_MAX} (@pxref{Range of Type}).
855 Like @code{strtol} this function sets @code{errno} and returns the value
856 @code{0ul} in case the value for @var{base} is not in the legal range.
857 For @code{strtoul} this can happen in another situation. In case the
858 number to be converted is negative @code{strtoul} also sets @code{errno}
859 to @code{EINVAL} and returns @code{0ul}.
864 @deftypefun {long long int} strtoll (const char *@var{string}, char **@var{tailptr}, int @var{base})
865 The @code{strtoll} function is like @code{strtol} except that is deals
866 with extra long numbers and it returns its value with type @code{long
869 If the string has valid syntax for an integer but the value is not
870 representable because of overflow, @code{strtoll} returns either
871 @code{LONG_LONG_MAX} or @code{LONG_LONG_MIN} (@pxref{Range of Type}), as
872 appropriate for the sign of the value. It also sets @code{errno} to
873 @code{ERANGE} to indicate there was overflow.
875 The @code{strtoll} function is a GNU extension but it will eventually be
876 part of the next ISO C standard.
881 @deftypefun {long long int} strtoq (const char *@var{string}, char **@var{tailptr}, int @var{base})
882 @code{strtoq} (``string-to-quad-word'') is only an commonly used other
883 name for the @code{strtoll} function. Everything said for
884 @code{strtoll} applies to @code{strtoq} as well.
889 @deftypefun {unsigned long long int} strtoull (const char *@var{string}, char **@var{tailptr}, int @var{base})
890 The @code{strtoull} function is like @code{strtoul} except that is deals
891 with extra long numbers and it returns its value with type
892 @code{unsigned long long int}. The value returned in case of overflow
893 is @code{ULONG_LONG_MAX} (@pxref{Range of Type}).
895 The @code{strtoull} function is a GNU extension but it will eventually be
896 part of the next ISO C standard.
901 @deftypefun {unsigned long long int} strtouq (const char *@var{string}, char **@var{tailptr}, int @var{base})
902 @code{strtouq} (``string-to-unsigned-quad-word'') is only an commonly
903 used other name for the @code{strtoull} function. Everything said for
904 @code{strtoull} applies to @code{strtouq} as well.
909 @deftypefun {long int} atol (const char *@var{string})
910 This function is similar to the @code{strtol} function with a @var{base}
911 argument of @code{10}, except that it need not detect overflow errors.
912 The @code{atol} function is provided mostly for compatibility with
913 existing code; using @code{strtol} is more robust.
918 @deftypefun int atoi (const char *@var{string})
919 This function is like @code{atol}, except that it returns an @code{int}
920 value rather than @code{long int}. The @code{atoi} function is also
921 considered obsolete; use @code{strtol} instead.
926 @deftypefun {long long int} atoll (const char *@var{string})
927 This function is similar to @code{atol}, except it returns a @code{long
928 long int} value rather than @code{long int}.
930 The @code{atoll} function is a GNU extension but it will eventually be
931 part of the next ISO C standard.
934 The POSIX locales contain some information about how to format numbers
935 (@pxref{General Numeric}). This mainly deals with representing numbers
936 for better readability for humans. The functions present so far in this
937 section cannot handle numbers in this form.
939 If this functionality is needed in a program one can use the functions
940 from the @code{scanf} family which know about the flag @samp{'} for
941 parsing numeric input (@pxref{Numeric Input Conversions}). Sometimes it
942 is more desirable to have finer control.
944 In these situation one could use the function
945 @code{__strto@var{XXX}_internal}. @var{XXX} here stands for any of the
946 above forms. All numeric conversion functions (including the functions
947 to process floating-point numbers) have such a counterpart. The
948 difference to the normal form is the extra argument at the end of the
949 parameter list. If this value has an non-zero value the handling of
950 number grouping is enabled. The advantage of using these functions is
951 that the @var{tailptr} parameters allow to determine which part of the
952 input is processed. The @code{scanf} functions don't provide this
953 information. The drawback of using these functions is that they are not
954 portable. They only exist in the GNU C library.
957 Here is a function which parses a string as a sequence of integers and
958 returns the sum of them:
962 sum_ints_from_string (char *string)
970 /* @r{Skip whitespace by hand, to detect the end.} */
971 while (isspace (*string)) string++;
975 /* @r{There is more nonwhitespace,} */
976 /* @r{so it ought to be another number.} */
979 next = strtol (string, &tail, 0);
980 /* @r{Add it in, if not overflow.} */
982 printf ("Overflow\n");
985 /* @r{Advance past it.} */
993 @node Parsing of Floats
994 @subsection Parsing of Floats
997 These functions are declared in @file{stdlib.h}.
1001 @deftypefun double strtod (const char *@var{string}, char **@var{tailptr})
1002 The @code{strtod} (``string-to-double'') function converts the initial
1003 part of @var{string} to a floating-point number, which is returned as a
1004 value of type @code{double}.
1006 This function attempts to decompose @var{string} as follows:
1010 A (possibly empty) sequence of whitespace characters. Which characters
1011 are whitespace is determined by the @code{isspace} function
1012 (@pxref{Classification of Characters}). These are discarded.
1015 An optional plus or minus sign (@samp{+} or @samp{-}).
1018 A nonempty sequence of digits optionally containing a decimal-point
1019 character---normally @samp{.}, but it depends on the locale
1020 (@pxref{Numeric Formatting}).
1023 An optional exponent part, consisting of a character @samp{e} or
1024 @samp{E}, an optional sign, and a sequence of digits.
1027 Any remaining characters in the string. If @var{tailptr} is not a null
1028 pointer, a pointer to this tail of the string is stored in
1029 @code{*@var{tailptr}}.
1032 If the string is empty, contains only whitespace, or does not contain an
1033 initial substring that has the expected syntax for a floating-point
1034 number, no conversion is performed. In this case, @code{strtod} returns
1035 a value of zero and the value returned in @code{*@var{tailptr}} is the
1036 value of @var{string}.
1038 In a locale other than the standard @code{"C"} or @code{"POSIX"} locales,
1039 this function may recognize additional locale-dependent syntax.
1041 If the string has valid syntax for a floating-point number but the value
1042 is not representable because of overflow, @code{strtod} returns either
1043 positive or negative @code{HUGE_VAL} (@pxref{Mathematics}), depending on
1044 the sign of the value. Similarly, if the value is not representable
1045 because of underflow, @code{strtod} returns zero. It also sets @code{errno}
1046 to @code{ERANGE} if there was overflow or underflow.
1048 There are two more special inputs which are recognized by @code{strtod}.
1049 The string @code{"inf"} or @code{"infinity"} (without consideration of
1050 case and optionally preceded by a @code{"+"} or @code{"-"} sign) is
1051 changed to the floating-point value for infinity if the floating-point
1052 format supports this; and to the largest representable value otherwise.
1054 If the input string is @code{"nan"} or
1055 @code{"nan(@var{n-char-sequence})"} the return value of @code{strtod} is
1056 the representation of the NaN (not a number) value (if the
1057 flaoting-point formats supports this. The form with the
1058 @var{n-char-sequence} enables in an implementation specific way to
1059 specify the form of the NaN value. When using the @w{IEEE 754}
1060 floating-point format, the NaN value can have a lot of forms since only
1061 at least one bit in the mantissa must be set. In the GNU C library
1062 implementation of @code{strtod} the @var{n-char-sequence} is interpreted
1063 as a number (as recognized by @code{strtol}, @pxref{Parsing of Integers})
1064 The mantissa of the return value corresponds to this given number.
1066 Since the value zero which is returned in the error case is also a valid
1067 result the user should set the global variable @code{errno} to zero
1068 before calling this function. So one can test for failures after the
1069 call since all failures set @code{errno} to a non-zero value.
1074 @deftypefun float strtof (const char *@var{string}, char **@var{tailptr})
1075 This function is similar to the @code{strtod} function but it returns a
1076 @code{float} value instead of a @code{double} value. If the precision
1077 of a @code{float} value is sufficient this function should be used since
1078 it is much faster than @code{strtod} on some architectures. The reasons
1079 are obvious: @w{IEEE 754} defines @code{float} to have a mantissa of 23
1080 bits while @code{double} has 53 bits and every additional bit of
1081 precision can require additional computation.
1083 If the string has valid syntax for a floating-point number but the value
1084 is not representable because of overflow, @code{strtof} returns either
1085 positive or negative @code{HUGE_VALF} (@pxref{Mathematics}), depending on
1086 the sign of the value.
1088 This function is a GNU extension.
1093 @deftypefun {long double} strtold (const char *@var{string}, char **@var{tailptr})
1094 This function is similar to the @code{strtod} function but it returns a
1095 @code{long double} value instead of a @code{double} value. It should be
1096 used when high precision is needed. On systems which define a @code{long
1097 double} type (i.e., on which it is not the same as @code{double})
1098 running this function might take significantly more time since more bits
1099 of precision are required.
1101 If the string has valid syntax for a floating-point number but the value
1102 is not representable because of overflow, @code{strtold} returns either
1103 positive or negative @code{HUGE_VALL} (@pxref{Mathematics}), depending on
1104 the sign of the value.
1106 This function is a GNU extension.
1109 As for the integer parsing functions there are additional functions
1110 which will handle numbers represented using the grouping scheme of the
1111 current locale (@pxref{Parsing of Integers}).
1115 @deftypefun double atof (const char *@var{string})
1116 This function is similar to the @code{strtod} function, except that it
1117 need not detect overflow and underflow errors. The @code{atof} function
1118 is provided mostly for compatibility with existing code; using
1119 @code{strtod} is more robust.