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:: Classify 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 An expression representing the infinite value. @code{INFINITY} values are
45 produced 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{-INFINITY} is representable
51 and it is handled differently if needed. It is possible to test a
52 value for infiniteness 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 convenience 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 @deftypefn {Macro} 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 @deftypefn {Macro} 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 @deftypefn {Macro} 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 @deftypefn {Macro} 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 advantages:
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 requires 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 infinite on the real axis. If the
361 real part is infinite, the result is equivalent to
364 INFINITY + I * copysign (0.0, cimag (z))
370 @section Absolute Value
371 @cindex absolute value functions
373 These functions are provided for obtaining the @dfn{absolute value} (or
374 @dfn{magnitude}) of a number. The absolute value of a real number
375 @var{x} is @var{x} is @var{x} is positive, @minus{}@var{x} if @var{x} is
376 negative. For a complex number @var{z}, whose real part is @var{x} and
377 whose imaginary part is @var{y}, the absolute value is @w{@code{sqrt
378 (@var{x}*@var{x} + @var{y}*@var{y})}}.
382 Prototypes for @code{abs} and @code{labs} are in @file{stdlib.h};
383 @code{fabs}, @code{fabsf} and @code{fabsl} are declared in @file{math.h};
384 @code{cabs}, @code{cabsf} and @code{cabsl} are declared in @file{complex.h}.
388 @deftypefun int abs (int @var{number})
389 This function returns the absolute value of @var{number}.
391 Most computers use a two's complement integer representation, in which
392 the absolute value of @code{INT_MIN} (the smallest possible @code{int})
393 cannot be represented; thus, @w{@code{abs (INT_MIN)}} is not defined.
398 @deftypefun {long int} labs (long int @var{number})
399 This is similar to @code{abs}, except that both the argument and result
400 are of type @code{long int} rather than @code{int}.
405 @deftypefun double fabs (double @var{number})
406 @deftypefunx float fabsf (float @var{number})
407 @deftypefunx {long double} fabsl (long double @var{number})
408 This function returns the absolute value of the floating-point number
414 @deftypefun double cabs (complex double @var{z})
415 @deftypefunx float cabsf (complex float @var{z})
416 @deftypefunx {long double} cabsl (complex long double @var{z})
417 These functions return the absolute value of the complex number @var{z}.
418 The compiler must support complex numbers to use these functions. The
422 sqrt (creal (@var{z}) * creal (@var{z}) + cimag (@var{z}) * cimag (@var{z}))
425 This function should always be used instead of the direct formula since
426 using the simple straight-forward method can mean to lose accuracy. If
427 one of the squared values is neglectable in size compared to the other
428 value the result should be the same as the larger value. But squaring
429 the value and afterwards using the square root function leads to
430 inaccuracy. See @code{hypot} in @xref{Exponents and Logarithms}.
433 @node Normalization Functions
434 @section Normalization Functions
435 @cindex normalization functions (floating-point)
437 The functions described in this section are primarily provided as a way
438 to efficiently perform certain low-level manipulations on floating point
439 numbers that are represented internally using a binary radix;
440 see @ref{Floating Point Concepts}. These functions are required to
441 have equivalent behavior even if the representation does not use a radix
442 of 2, but of course they are unlikely to be particularly efficient in
446 All these functions are declared in @file{math.h}.
450 @deftypefun double frexp (double @var{value}, int *@var{exponent})
451 @deftypefunx float frexpf (float @var{value}, int *@var{exponent})
452 @deftypefunx {long double} frexpl (long double @var{value}, int *@var{exponent})
453 These functions are used to split the number @var{value}
454 into a normalized fraction and an exponent.
456 If the argument @var{value} is not zero, the return value is @var{value}
457 times a power of two, and is always in the range 1/2 (inclusive) to 1
458 (exclusive). The corresponding exponent is stored in
459 @code{*@var{exponent}}; the return value multiplied by 2 raised to this
460 exponent equals the original number @var{value}.
462 For example, @code{frexp (12.8, &exponent)} returns @code{0.8} and
463 stores @code{4} in @code{exponent}.
465 If @var{value} is zero, then the return value is zero and
466 zero is stored in @code{*@var{exponent}}.
471 @deftypefun double ldexp (double @var{value}, int @var{exponent})
472 @deftypefunx float ldexpf (float @var{value}, int @var{exponent})
473 @deftypefunx {long double} ldexpl (long double @var{value}, int @var{exponent})
474 These functions return the result of multiplying the floating-point
475 number @var{value} by 2 raised to the power @var{exponent}. (It can
476 be used to reassemble floating-point numbers that were taken apart
479 For example, @code{ldexp (0.8, 4)} returns @code{12.8}.
482 The following functions which come from BSD provide facilities
483 equivalent to those of @code{ldexp} and @code{frexp}:
487 @deftypefun double scalb (double @var{value}, int @var{exponent})
488 @deftypefunx float scalbf (float @var{value}, int @var{exponent})
489 @deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent})
490 The @code{scalb} function is the BSD name for @code{ldexp}.
495 @deftypefun double logb (double @var{x})
496 @deftypefunx float logbf (float @var{x})
497 @deftypefunx {long double} logbl (long double @var{x})
498 These BSD functions return the integer part of the base-2 logarithm of
499 @var{x}, an integer value represented in type @code{double}. This is
500 the highest integer power of @code{2} contained in @var{x}. The sign of
501 @var{x} is ignored. For example, @code{logb (3.5)} is @code{1.0} and
502 @code{logb (4.0)} is @code{2.0}.
504 When @code{2} raised to this power is divided into @var{x}, it gives a
505 quotient between @code{1} (inclusive) and @code{2} (exclusive).
507 If @var{x} is zero, the value is minus infinity (if the machine supports
508 such a value), or else a very small number. If @var{x} is infinity, the
511 The value returned by @code{logb} is one less than the value that
512 @code{frexp} would store into @code{*@var{exponent}}.
517 @deftypefun double copysign (double @var{value}, double @var{sign})
518 @deftypefunx float copysignf (float @var{value}, float @var{sign})
519 @deftypefunx {long double} copysignl (long double @var{value}, long double @var{sign})
520 These functions return a value whose absolute value is the
521 same as that of @var{value}, and whose sign matches that of @var{sign}.
522 This function appears in BSD and was standardized in @w{ISO C 9X}.
527 @deftypefun int signbit (@emph{float-type} @var{x})
528 @code{signbit} is a generic macro which can work on all floating-point
529 types. It returns a nonzero value if the value of @var{x} has its sign
532 This is not the same as @code{x < 0.0} since in some floating-point
533 formats (e.g., @w{IEEE 754}) the zero value is optionally signed. The
534 comparison @code{-0.0 < 0.0} will not be true while @code{signbit
535 (-0.0)} will return a nonzero value.
538 @node Rounding and Remainders
539 @section Rounding and Remainder Functions
540 @cindex rounding functions
541 @cindex remainder functions
542 @cindex converting floats to integers
545 The functions listed here perform operations such as rounding,
546 truncation, and remainder in division of floating point numbers. Some
547 of these functions convert floating point numbers to integer values.
548 They are all declared in @file{math.h}.
550 You can also convert floating-point numbers to integers simply by
551 casting them to @code{int}. This discards the fractional part,
552 effectively rounding towards zero. However, this only works if the
553 result can actually be represented as an @code{int}---for very large
554 numbers, this is impossible. The functions listed here return the
555 result as a @code{double} instead to get around this problem.
559 @deftypefun double ceil (double @var{x})
560 @deftypefunx float ceilf (float @var{x})
561 @deftypefunx {long double} ceill (long double @var{x})
562 These functions round @var{x} upwards to the nearest integer,
563 returning that value as a @code{double}. Thus, @code{ceil (1.5)}
569 @deftypefun double floor (double @var{x})
570 @deftypefunx float floorf (float @var{x})
571 @deftypefunx {long double} floorl (long double @var{x})
572 These functions round @var{x} downwards to the nearest
573 integer, returning that value as a @code{double}. Thus, @code{floor
574 (1.5)} is @code{1.0} and @code{floor (-1.5)} is @code{-2.0}.
579 @deftypefun double rint (double @var{x})
580 @deftypefunx float rintf (float @var{x})
581 @deftypefunx {long double} rintl (long double @var{x})
582 These functions round @var{x} to an integer value according to the
583 current rounding mode. @xref{Floating Point Parameters}, for
584 information about the various rounding modes. The default
585 rounding mode is to round to the nearest integer; some machines
586 support other modes, but round-to-nearest is always used unless
587 you explicit select another.
592 @deftypefun double nearbyint (double @var{x})
593 @deftypefunx float nearbyintf (float @var{x})
594 @deftypefunx {long double} nearbyintl (long double @var{x})
595 These functions return the same value as the @code{rint} functions but
596 even some rounding actually takes place @code{nearbyint} does @emph{not}
597 raise the inexact exception.
602 @deftypefun double modf (double @var{value}, double *@var{integer-part})
603 @deftypefunx float modff (float @var{value}, float *@var{integer-part})
604 @deftypefunx {long double} modfl (long double @var{value}, long double *@var{integer-part})
605 These functions break the argument @var{value} into an integer part and a
606 fractional part (between @code{-1} and @code{1}, exclusive). Their sum
607 equals @var{value}. Each of the parts has the same sign as @var{value},
608 so the rounding of the integer part is towards zero.
610 @code{modf} stores the integer part in @code{*@var{integer-part}}, and
611 returns the fractional part. For example, @code{modf (2.5, &intpart)}
612 returns @code{0.5} and stores @code{2.0} into @code{intpart}.
617 @deftypefun double fmod (double @var{numerator}, double @var{denominator})
618 @deftypefunx float fmodf (float @var{numerator}, float @var{denominator})
619 @deftypefunx {long double} fmodl (long double @var{numerator}, long double @var{denominator})
620 These functions compute the remainder from the division of
621 @var{numerator} by @var{denominator}. Specifically, the return value is
622 @code{@var{numerator} - @w{@var{n} * @var{denominator}}}, where @var{n}
623 is the quotient of @var{numerator} divided by @var{denominator}, rounded
624 towards zero to an integer. Thus, @w{@code{fmod (6.5, 2.3)}} returns
625 @code{1.9}, which is @code{6.5} minus @code{4.6}.
627 The result has the same sign as the @var{numerator} and has magnitude
628 less than the magnitude of the @var{denominator}.
630 If @var{denominator} is zero, @code{fmod} fails and sets @code{errno} to
636 @deftypefun double drem (double @var{numerator}, double @var{denominator})
637 @deftypefunx float dremf (float @var{numerator}, float @var{denominator})
638 @deftypefunx {long double} dreml (long double @var{numerator}, long double @var{denominator})
639 These functions are like @code{fmod} etc except that it rounds the
640 internal quotient @var{n} to the nearest integer instead of towards zero
641 to an integer. For example, @code{drem (6.5, 2.3)} returns @code{-0.4},
642 which is @code{6.5} minus @code{6.9}.
644 The absolute value of the result is less than or equal to half the
645 absolute value of the @var{denominator}. The difference between
646 @code{fmod (@var{numerator}, @var{denominator})} and @code{drem
647 (@var{numerator}, @var{denominator})} is always either
648 @var{denominator}, minus @var{denominator}, or zero.
650 If @var{denominator} is zero, @code{drem} fails and sets @code{errno} to
655 @node Integer Division
656 @section Integer Division
657 @cindex integer division functions
659 This section describes functions for performing integer division. These
660 functions are redundant in the GNU C library, since in GNU C the @samp{/}
661 operator always rounds towards zero. But in other C implementations,
662 @samp{/} may round differently with negative arguments. @code{div} and
663 @code{ldiv} are useful because they specify how to round the quotient:
664 towards zero. The remainder has the same sign as the numerator.
666 These functions are specified to return a result @var{r} such that the value
667 @code{@var{r}.quot*@var{denominator} + @var{r}.rem} equals
671 To use these facilities, you should include the header file
672 @file{stdlib.h} in your program.
676 @deftp {Data Type} div_t
677 This is a structure type used to hold the result returned by the @code{div}
678 function. It has the following members:
682 The quotient from the division.
685 The remainder from the division.
691 @deftypefun div_t div (int @var{numerator}, int @var{denominator})
692 This function @code{div} computes the quotient and remainder from
693 the division of @var{numerator} by @var{denominator}, returning the
694 result in a structure of type @code{div_t}.
696 If the result cannot be represented (as in a division by zero), the
697 behavior is undefined.
699 Here is an example, albeit not a very useful one.
703 result = div (20, -6);
707 Now @code{result.quot} is @code{-3} and @code{result.rem} is @code{2}.
712 @deftp {Data Type} ldiv_t
713 This is a structure type used to hold the result returned by the @code{ldiv}
714 function. It has the following members:
718 The quotient from the division.
721 The remainder from the division.
724 (This is identical to @code{div_t} except that the components are of
725 type @code{long int} rather than @code{int}.)
730 @deftypefun ldiv_t ldiv (long int @var{numerator}, long int @var{denominator})
731 The @code{ldiv} function is similar to @code{div}, except that the
732 arguments are of type @code{long int} and the result is returned as a
733 structure of type @code{ldiv_t}.
738 @deftp {Data Type} lldiv_t
739 This is a structure type used to hold the result returned by the @code{lldiv}
740 function. It has the following members:
743 @item long long int quot
744 The quotient from the division.
746 @item long long int rem
747 The remainder from the division.
750 (This is identical to @code{div_t} except that the components are of
751 type @code{long long int} rather than @code{int}.)
756 @deftypefun lldiv_t lldiv (long long int @var{numerator}, long long int @var{denominator})
757 The @code{lldiv} function is like the @code{div} function, but the
758 arguments are of type @code{long long int} and the result is returned as
759 a structure of type @code{lldiv_t}.
761 The @code{lldiv} function is a GNU extension but it will eventually be
762 part of the next ISO C standard.
766 @node Parsing of Numbers
767 @section Parsing of Numbers
768 @cindex parsing numbers (in formatted input)
769 @cindex converting strings to numbers
770 @cindex number syntax, parsing
771 @cindex syntax, for reading numbers
773 This section describes functions for ``reading'' integer and
774 floating-point numbers from a string. It may be more convenient in some
775 cases to use @code{sscanf} or one of the related functions; see
776 @ref{Formatted Input}. But often you can make a program more robust by
777 finding the tokens in the string by hand, then converting the numbers
781 * Parsing of Integers:: Functions for conversion of integer values.
782 * Parsing of Floats:: Functions for conversion of floating-point
786 @node Parsing of Integers
787 @subsection Parsing of Integers
790 These functions are declared in @file{stdlib.h}.
794 @deftypefun {long int} strtol (const char *@var{string}, char **@var{tailptr}, int @var{base})
795 The @code{strtol} (``string-to-long'') function converts the initial
796 part of @var{string} to a signed integer, which is returned as a value
797 of type @code{long int}.
799 This function attempts to decompose @var{string} as follows:
803 A (possibly empty) sequence of whitespace characters. Which characters
804 are whitespace is determined by the @code{isspace} function
805 (@pxref{Classification of Characters}). These are discarded.
808 An optional plus or minus sign (@samp{+} or @samp{-}).
811 A nonempty sequence of digits in the radix specified by @var{base}.
813 If @var{base} is zero, decimal radix is assumed unless the series of
814 digits begins with @samp{0} (specifying octal radix), or @samp{0x} or
815 @samp{0X} (specifying hexadecimal radix); in other words, the same
816 syntax used for integer constants in C.
818 Otherwise @var{base} must have a value between @code{2} and @code{35}.
819 If @var{base} is @code{16}, the digits may optionally be preceded by
820 @samp{0x} or @samp{0X}. If base has no legal value the value returned
821 is @code{0l} and the global variable @code{errno} is set to @code{EINVAL}.
824 Any remaining characters in the string. If @var{tailptr} is not a null
825 pointer, @code{strtol} stores a pointer to this tail in
826 @code{*@var{tailptr}}.
829 If the string is empty, contains only whitespace, or does not contain an
830 initial substring that has the expected syntax for an integer in the
831 specified @var{base}, no conversion is performed. In this case,
832 @code{strtol} returns a value of zero and the value stored in
833 @code{*@var{tailptr}} is the value of @var{string}.
835 In a locale other than the standard @code{"C"} locale, this function
836 may recognize additional implementation-dependent syntax.
838 If the string has valid syntax for an integer but the value is not
839 representable because of overflow, @code{strtol} returns either
840 @code{LONG_MAX} or @code{LONG_MIN} (@pxref{Range of Type}), as
841 appropriate for the sign of the value. It also sets @code{errno}
842 to @code{ERANGE} to indicate there was overflow.
844 Because the value @code{0l} is a correct result for @code{strtol} the
845 user who is interested in handling errors should set the global variable
846 @code{errno} to @code{0} before calling this function, so that the program
847 can later test whether an error occurred.
849 There is an example at the end of this section.
854 @deftypefun {unsigned long int} strtoul (const char *@var{string}, char **@var{tailptr}, int @var{base})
855 The @code{strtoul} (``string-to-unsigned-long'') function is like
856 @code{strtol} except it deals with unsigned numbers, and returns its
857 value with type @code{unsigned long int}. No @samp{+} or @samp{-} sign
858 may appear before the number, but the syntax is otherwise the same as
859 described above for @code{strtol}. The value returned in case of
860 overflow is @code{ULONG_MAX} (@pxref{Range of Type}).
862 Like @code{strtol} this function sets @code{errno} and returns the value
863 @code{0ul} in case the value for @var{base} is not in the legal range.
864 For @code{strtoul} this can happen in another situation. In case the
865 number to be converted is negative @code{strtoul} also sets @code{errno}
866 to @code{EINVAL} and returns @code{0ul}.
871 @deftypefun {long long int} strtoll (const char *@var{string}, char **@var{tailptr}, int @var{base})
872 The @code{strtoll} function is like @code{strtol} except that is deals
873 with extra long numbers and it returns its value with type @code{long
876 If the string has valid syntax for an integer but the value is not
877 representable because of overflow, @code{strtoll} returns either
878 @code{LONG_LONG_MAX} or @code{LONG_LONG_MIN} (@pxref{Range of Type}), as
879 appropriate for the sign of the value. It also sets @code{errno} to
880 @code{ERANGE} to indicate there was overflow.
882 The @code{strtoll} function is a GNU extension but it will eventually be
883 part of the next ISO C standard.
888 @deftypefun {long long int} strtoq (const char *@var{string}, char **@var{tailptr}, int @var{base})
889 @code{strtoq} (``string-to-quad-word'') is only an commonly used other
890 name for the @code{strtoll} function. Everything said for
891 @code{strtoll} applies to @code{strtoq} as well.
896 @deftypefun {unsigned long long int} strtoull (const char *@var{string}, char **@var{tailptr}, int @var{base})
897 The @code{strtoull} function is like @code{strtoul} except that is deals
898 with extra long numbers and it returns its value with type
899 @code{unsigned long long int}. The value returned in case of overflow
900 is @code{ULONG_LONG_MAX} (@pxref{Range of Type}).
902 The @code{strtoull} function is a GNU extension but it will eventually be
903 part of the next ISO C standard.
908 @deftypefun {unsigned long long int} strtouq (const char *@var{string}, char **@var{tailptr}, int @var{base})
909 @code{strtouq} (``string-to-unsigned-quad-word'') is only an commonly
910 used other name for the @code{strtoull} function. Everything said for
911 @code{strtoull} applies to @code{strtouq} as well.
916 @deftypefun {long int} atol (const char *@var{string})
917 This function is similar to the @code{strtol} function with a @var{base}
918 argument of @code{10}, except that it need not detect overflow errors.
919 The @code{atol} function is provided mostly for compatibility with
920 existing code; using @code{strtol} is more robust.
925 @deftypefun int atoi (const char *@var{string})
926 This function is like @code{atol}, except that it returns an @code{int}
927 value rather than @code{long int}. The @code{atoi} function is also
928 considered obsolete; use @code{strtol} instead.
933 @deftypefun {long long int} atoll (const char *@var{string})
934 This function is similar to @code{atol}, except it returns a @code{long
935 long int} value rather than @code{long int}.
937 The @code{atoll} function is a GNU extension but it will eventually be
938 part of the next ISO C standard.
941 The POSIX locales contain some information about how to format numbers
942 (@pxref{General Numeric}). This mainly deals with representing numbers
943 for better readability for humans. The functions present so far in this
944 section cannot handle numbers in this form.
946 If this functionality is needed in a program one can use the functions
947 from the @code{scanf} family which know about the flag @samp{'} for
948 parsing numeric input (@pxref{Numeric Input Conversions}). Sometimes it
949 is more desirable to have finer control.
951 In these situation one could use the function
952 @code{__strto@var{XXX}_internal}. @var{XXX} here stands for any of the
953 above forms. All numeric conversion functions (including the functions
954 to process floating-point numbers) have such a counterpart. The
955 difference to the normal form is the extra argument at the end of the
956 parameter list. If this value has an non-zero value the handling of
957 number grouping is enabled. The advantage of using these functions is
958 that the @var{tailptr} parameters allow to determine which part of the
959 input is processed. The @code{scanf} functions don't provide this
960 information. The drawback of using these functions is that they are not
961 portable. They only exist in the GNU C library.
964 Here is a function which parses a string as a sequence of integers and
965 returns the sum of them:
969 sum_ints_from_string (char *string)
977 /* @r{Skip whitespace by hand, to detect the end.} */
978 while (isspace (*string)) string++;
982 /* @r{There is more nonwhitespace,} */
983 /* @r{so it ought to be another number.} */
986 next = strtol (string, &tail, 0);
987 /* @r{Add it in, if not overflow.} */
989 printf ("Overflow\n");
992 /* @r{Advance past it.} */
1000 @node Parsing of Floats
1001 @subsection Parsing of Floats
1004 These functions are declared in @file{stdlib.h}.
1008 @deftypefun double strtod (const char *@var{string}, char **@var{tailptr})
1009 The @code{strtod} (``string-to-double'') function converts the initial
1010 part of @var{string} to a floating-point number, which is returned as a
1011 value of type @code{double}.
1013 This function attempts to decompose @var{string} as follows:
1017 A (possibly empty) sequence of whitespace characters. Which characters
1018 are whitespace is determined by the @code{isspace} function
1019 (@pxref{Classification of Characters}). These are discarded.
1022 An optional plus or minus sign (@samp{+} or @samp{-}).
1025 A nonempty sequence of digits optionally containing a decimal-point
1026 character---normally @samp{.}, but it depends on the locale
1027 (@pxref{Numeric Formatting}).
1030 An optional exponent part, consisting of a character @samp{e} or
1031 @samp{E}, an optional sign, and a sequence of digits.
1034 Any remaining characters in the string. If @var{tailptr} is not a null
1035 pointer, a pointer to this tail of the string is stored in
1036 @code{*@var{tailptr}}.
1039 If the string is empty, contains only whitespace, or does not contain an
1040 initial substring that has the expected syntax for a floating-point
1041 number, no conversion is performed. In this case, @code{strtod} returns
1042 a value of zero and the value returned in @code{*@var{tailptr}} is the
1043 value of @var{string}.
1045 In a locale other than the standard @code{"C"} or @code{"POSIX"} locales,
1046 this function may recognize additional locale-dependent syntax.
1048 If the string has valid syntax for a floating-point number but the value
1049 is not representable because of overflow, @code{strtod} returns either
1050 positive or negative @code{HUGE_VAL} (@pxref{Mathematics}), depending on
1051 the sign of the value. Similarly, if the value is not representable
1052 because of underflow, @code{strtod} returns zero. It also sets @code{errno}
1053 to @code{ERANGE} if there was overflow or underflow.
1055 There are two more special inputs which are recognized by @code{strtod}.
1056 The string @code{"inf"} or @code{"infinity"} (without consideration of
1057 case and optionally preceded by a @code{"+"} or @code{"-"} sign) is
1058 changed to the floating-point value for infinity if the floating-point
1059 format supports this; and to the largest representable value otherwise.
1061 If the input string is @code{"nan"} or
1062 @code{"nan(@var{n-char-sequence})"} the return value of @code{strtod} is
1063 the representation of the NaN (not a number) value (if the
1064 floating-point format supports this). In the second form the part
1065 @var{n-char-sequence} allows to specify the form of the NaN value in an
1066 implementation specific way. When using the @w{IEEE 754}
1067 floating-point format, the NaN value can have a lot of forms since only
1068 at least one bit in the mantissa must be set. In the GNU C library
1069 implementation of @code{strtod} the @var{n-char-sequence} is interpreted
1070 as a number (as recognized by @code{strtol}, @pxref{Parsing of Integers}).
1071 The mantissa of the return value corresponds to this given number.
1073 Since the value zero which is returned in the error case is also a valid
1074 result the user should set the global variable @code{errno} to zero
1075 before calling this function. So one can test for failures after the
1076 call since all failures set @code{errno} to a non-zero value.
1081 @deftypefun float strtof (const char *@var{string}, char **@var{tailptr})
1082 This function is similar to the @code{strtod} function but it returns a
1083 @code{float} value instead of a @code{double} value. If the precision
1084 of a @code{float} value is sufficient this function should be used since
1085 it is much faster than @code{strtod} on some architectures. The reasons
1086 are obvious: @w{IEEE 754} defines @code{float} to have a mantissa of 23
1087 bits while @code{double} has 53 bits and every additional bit of
1088 precision can require additional computation.
1090 If the string has valid syntax for a floating-point number but the value
1091 is not representable because of overflow, @code{strtof} returns either
1092 positive or negative @code{HUGE_VALF} (@pxref{Mathematics}), depending on
1093 the sign of the value.
1095 This function is a GNU extension.
1100 @deftypefun {long double} strtold (const char *@var{string}, char **@var{tailptr})
1101 This function is similar to the @code{strtod} function but it returns a
1102 @code{long double} value instead of a @code{double} value. It should be
1103 used when high precision is needed. On systems which define a @code{long
1104 double} type (i.e., on which it is not the same as @code{double})
1105 running this function might take significantly more time since more bits
1106 of precision are required.
1108 If the string has valid syntax for a floating-point number but the value
1109 is not representable because of overflow, @code{strtold} returns either
1110 positive or negative @code{HUGE_VALL} (@pxref{Mathematics}), depending on
1111 the sign of the value.
1113 This function is a GNU extension.
1116 As for the integer parsing functions there are additional functions
1117 which will handle numbers represented using the grouping scheme of the
1118 current locale (@pxref{Parsing of Integers}).
1122 @deftypefun double atof (const char *@var{string})
1123 This function is similar to the @code{strtod} function, except that it
1124 need not detect overflow and underflow errors. The @code{atof} function
1125 is provided mostly for compatibility with existing code; using
1126 @code{strtod} is more robust.