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 @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 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. The
421 sqrt (creal (@var{z}) * creal (@var{z}) + cimag (@var{z}) * cimag (@var{z}))
424 This function should always be used instead of the direct formula since
425 using the simple straight-forward method can mean to loose accuracy. If
426 one of the squared values is neglectable in size compared to the other
427 value the result should be the same as the larger value. But squaring
428 the value and afterwards using the square root function leads to
429 unaccuracy. See @code{hypot} in @xref{Exponents and Logarithms}.
432 @node Normalization Functions
433 @section Normalization Functions
434 @cindex normalization functions (floating-point)
436 The functions described in this section are primarily provided as a way
437 to efficiently perform certain low-level manipulations on floating point
438 numbers that are represented internally using a binary radix;
439 see @ref{Floating Point Concepts}. These functions are required to
440 have equivalent behavior even if the representation does not use a radix
441 of 2, but of course they are unlikely to be particularly efficient in
445 All these functions are declared in @file{math.h}.
449 @deftypefun double frexp (double @var{value}, int *@var{exponent})
450 @deftypefunx float frexpf (float @var{value}, int *@var{exponent})
451 @deftypefunx {long double} frexpl (long double @var{value}, int *@var{exponent})
452 These functions are used to split the number @var{value}
453 into a normalized fraction and an exponent.
455 If the argument @var{value} is not zero, the return value is @var{value}
456 times a power of two, and is always in the range 1/2 (inclusive) to 1
457 (exclusive). The corresponding exponent is stored in
458 @code{*@var{exponent}}; the return value multiplied by 2 raised to this
459 exponent equals the original number @var{value}.
461 For example, @code{frexp (12.8, &exponent)} returns @code{0.8} and
462 stores @code{4} in @code{exponent}.
464 If @var{value} is zero, then the return value is zero and
465 zero is stored in @code{*@var{exponent}}.
470 @deftypefun double ldexp (double @var{value}, int @var{exponent})
471 @deftypefunx float ldexpf (float @var{value}, int @var{exponent})
472 @deftypefunx {long double} ldexpl (long double @var{value}, int @var{exponent})
473 These functions return the result of multiplying the floating-point
474 number @var{value} by 2 raised to the power @var{exponent}. (It can
475 be used to reassemble floating-point numbers that were taken apart
478 For example, @code{ldexp (0.8, 4)} returns @code{12.8}.
481 The following functions which come from BSD provide facilities
482 equivalent to those of @code{ldexp} and @code{frexp}:
486 @deftypefun double scalb (double @var{value}, int @var{exponent})
487 @deftypefunx float scalbf (float @var{value}, int @var{exponent})
488 @deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent})
489 The @code{scalb} function is the BSD name for @code{ldexp}.
494 @deftypefun double logb (double @var{x})
495 @deftypefunx float logbf (float @var{x})
496 @deftypefunx {long double} logbl (long double @var{x})
497 These BSD functions return the integer part of the base-2 logarithm of
498 @var{x}, an integer value represented in type @code{double}. This is
499 the highest integer power of @code{2} contained in @var{x}. The sign of
500 @var{x} is ignored. For example, @code{logb (3.5)} is @code{1.0} and
501 @code{logb (4.0)} is @code{2.0}.
503 When @code{2} raised to this power is divided into @var{x}, it gives a
504 quotient between @code{1} (inclusive) and @code{2} (exclusive).
506 If @var{x} is zero, the value is minus infinity (if the machine supports
507 such a value), or else a very small number. If @var{x} is infinity, the
510 The value returned by @code{logb} is one less than the value that
511 @code{frexp} would store into @code{*@var{exponent}}.
516 @deftypefun double copysign (double @var{value}, double @var{sign})
517 @deftypefunx float copysignf (float @var{value}, float @var{sign})
518 @deftypefunx {long double} copysignl (long double @var{value}, long double @var{sign})
519 These functions return a value whose absolute value is the
520 same as that of @var{value}, and whose sign matches that of @var{sign}.
521 This function appears in BSD and was standardized in @w{ISO C 9X}.
526 @deftypefun int signbit (@emph{float-type} @var{x})
527 @code{signbit} is a generic macro which can work on all floating-point
528 types. It returns a nonzero value if the value of @var{x} has its sign
531 This is not the same as @code{x < 0.0} since in some floating-point
532 formats (e.g., @w{IEEE 754}) the zero value is optionally signed. The
533 comparison @code{-0.0 < 0.0} will not be true while @code{signbit
534 (-0.0)} will return a nonzeri value.
537 @node Rounding and Remainders
538 @section Rounding and Remainder Functions
539 @cindex rounding functions
540 @cindex remainder functions
541 @cindex converting floats to integers
544 The functions listed here perform operations such as rounding,
545 truncation, and remainder in division of floating point numbers. Some
546 of these functions convert floating point numbers to integer values.
547 They are all declared in @file{math.h}.
549 You can also convert floating-point numbers to integers simply by
550 casting them to @code{int}. This discards the fractional part,
551 effectively rounding towards zero. However, this only works if the
552 result can actually be represented as an @code{int}---for very large
553 numbers, this is impossible. The functions listed here return the
554 result as a @code{double} instead to get around this problem.
558 @deftypefun double ceil (double @var{x})
559 @deftypefunx float ceilf (float @var{x})
560 @deftypefunx {long double} ceill (long double @var{x})
561 These functions round @var{x} upwards to the nearest integer,
562 returning that value as a @code{double}. Thus, @code{ceil (1.5)}
568 @deftypefun double floor (double @var{x})
569 @deftypefunx float floorf (float @var{x})
570 @deftypefunx {long double} floorl (long double @var{x})
571 These functions round @var{x} downwards to the nearest
572 integer, returning that value as a @code{double}. Thus, @code{floor
573 (1.5)} is @code{1.0} and @code{floor (-1.5)} is @code{-2.0}.
578 @deftypefun double rint (double @var{x})
579 @deftypefunx float rintf (float @var{x})
580 @deftypefunx {long double} rintl (long double @var{x})
581 These functions round @var{x} to an integer value according to the
582 current rounding mode. @xref{Floating Point Parameters}, for
583 information about the various rounding modes. The default
584 rounding mode is to round to the nearest integer; some machines
585 support other modes, but round-to-nearest is always used unless
586 you explicit select another.
591 @deftypefun double nearbyint (double @var{x})
592 @deftypefunx float nearbyintf (float @var{x})
593 @deftypefunx {long double} nearbyintl (long double @var{x})
594 These functions return the same value as the @code{rint} functions but
595 even some rounding actually takes place @code{nearbyint} does @emph{not}
596 raise the inexact exception.
601 @deftypefun double modf (double @var{value}, double *@var{integer-part})
602 @deftypefunx float modff (flaot @var{value}, float *@var{integer-part})
603 @deftypefunx {long double} modfl (long double @var{value}, long double *@var{integer-part})
604 These functions break the argument @var{value} into an integer part and a
605 fractional part (between @code{-1} and @code{1}, exclusive). Their sum
606 equals @var{value}. Each of the parts has the same sign as @var{value},
607 so the rounding of the integer part is towards zero.
609 @code{modf} stores the integer part in @code{*@var{integer-part}}, and
610 returns the fractional part. For example, @code{modf (2.5, &intpart)}
611 returns @code{0.5} and stores @code{2.0} into @code{intpart}.
616 @deftypefun double fmod (double @var{numerator}, double @var{denominator})
617 @deftypefunx float fmodf (float @var{numerator}, float @var{denominator})
618 @deftypefunx {long double} fmodl (long double @var{numerator}, long double @var{denominator})
619 These functions compute the remainder from the division of
620 @var{numerator} by @var{denominator}. Specifically, the return value is
621 @code{@var{numerator} - @w{@var{n} * @var{denominator}}}, where @var{n}
622 is the quotient of @var{numerator} divided by @var{denominator}, rounded
623 towards zero to an integer. Thus, @w{@code{fmod (6.5, 2.3)}} returns
624 @code{1.9}, which is @code{6.5} minus @code{4.6}.
626 The result has the same sign as the @var{numerator} and has magnitude
627 less than the magnitude of the @var{denominator}.
629 If @var{denominator} is zero, @code{fmod} fails and sets @code{errno} to
635 @deftypefun double drem (double @var{numerator}, double @var{denominator})
636 @deftypefunx float dremf (float @var{numerator}, float @var{denominator})
637 @deftypefunx {long double} dreml (long double @var{numerator}, long double @var{denominator})
638 These functions are like @code{fmod} etc except that it rounds the
639 internal quotient @var{n} to the nearest integer instead of towards zero
640 to an integer. For example, @code{drem (6.5, 2.3)} returns @code{-0.4},
641 which is @code{6.5} minus @code{6.9}.
643 The absolute value of the result is less than or equal to half the
644 absolute value of the @var{denominator}. The difference between
645 @code{fmod (@var{numerator}, @var{denominator})} and @code{drem
646 (@var{numerator}, @var{denominator})} is always either
647 @var{denominator}, minus @var{denominator}, or zero.
649 If @var{denominator} is zero, @code{drem} fails and sets @code{errno} to
654 @node Integer Division
655 @section Integer Division
656 @cindex integer division functions
658 This section describes functions for performing integer division. These
659 functions are redundant in the GNU C library, since in GNU C the @samp{/}
660 operator always rounds towards zero. But in other C implementations,
661 @samp{/} may round differently with negative arguments. @code{div} and
662 @code{ldiv} are useful because they specify how to round the quotient:
663 towards zero. The remainder has the same sign as the numerator.
665 These functions are specified to return a result @var{r} such that the value
666 @code{@var{r}.quot*@var{denominator} + @var{r}.rem} equals
670 To use these facilities, you should include the header file
671 @file{stdlib.h} in your program.
675 @deftp {Data Type} div_t
676 This is a structure type used to hold the result returned by the @code{div}
677 function. It has the following members:
681 The quotient from the division.
684 The remainder from the division.
690 @deftypefun div_t div (int @var{numerator}, int @var{denominator})
691 This function @code{div} computes the quotient and remainder from
692 the division of @var{numerator} by @var{denominator}, returning the
693 result in a structure of type @code{div_t}.
695 If the result cannot be represented (as in a division by zero), the
696 behavior is undefined.
698 Here is an example, albeit not a very useful one.
702 result = div (20, -6);
706 Now @code{result.quot} is @code{-3} and @code{result.rem} is @code{2}.
711 @deftp {Data Type} ldiv_t
712 This is a structure type used to hold the result returned by the @code{ldiv}
713 function. It has the following members:
717 The quotient from the division.
720 The remainder from the division.
723 (This is identical to @code{div_t} except that the components are of
724 type @code{long int} rather than @code{int}.)
729 @deftypefun ldiv_t ldiv (long int @var{numerator}, long int @var{denominator})
730 The @code{ldiv} function is similar to @code{div}, except that the
731 arguments are of type @code{long int} and the result is returned as a
732 structure of type @code{ldiv_t}.
737 @deftp {Data Type} lldiv_t
738 This is a structure type used to hold the result returned by the @code{lldiv}
739 function. It has the following members:
742 @item long long int quot
743 The quotient from the division.
745 @item long long int rem
746 The remainder from the division.
749 (This is identical to @code{div_t} except that the components are of
750 type @code{long long int} rather than @code{int}.)
755 @deftypefun lldiv_t lldiv (long long int @var{numerator}, long long int @var{denominator})
756 The @code{lldiv} function is like the @code{div} function, but the
757 arguments are of type @code{long long int} and the result is returned as
758 a structure of type @code{lldiv_t}.
760 The @code{lldiv} function is a GNU extension but it will eventually be
761 part of the next ISO C standard.
765 @node Parsing of Numbers
766 @section Parsing of Numbers
767 @cindex parsing numbers (in formatted input)
768 @cindex converting strings to numbers
769 @cindex number syntax, parsing
770 @cindex syntax, for reading numbers
772 This section describes functions for ``reading'' integer and
773 floating-point numbers from a string. It may be more convenient in some
774 cases to use @code{sscanf} or one of the related functions; see
775 @ref{Formatted Input}. But often you can make a program more robust by
776 finding the tokens in the string by hand, then converting the numbers
780 * Parsing of Integers:: Functions for conversion of integer values.
781 * Parsing of Floats:: Functions for conversion of floating-point
785 @node Parsing of Integers
786 @subsection Parsing of Integers
789 These functions are declared in @file{stdlib.h}.
793 @deftypefun {long int} strtol (const char *@var{string}, char **@var{tailptr}, int @var{base})
794 The @code{strtol} (``string-to-long'') function converts the initial
795 part of @var{string} to a signed integer, which is returned as a value
796 of type @code{long int}.
798 This function attempts to decompose @var{string} as follows:
802 A (possibly empty) sequence of whitespace characters. Which characters
803 are whitespace is determined by the @code{isspace} function
804 (@pxref{Classification of Characters}). These are discarded.
807 An optional plus or minus sign (@samp{+} or @samp{-}).
810 A nonempty sequence of digits in the radix specified by @var{base}.
812 If @var{base} is zero, decimal radix is assumed unless the series of
813 digits begins with @samp{0} (specifying octal radix), or @samp{0x} or
814 @samp{0X} (specifying hexadecimal radix); in other words, the same
815 syntax used for integer constants in C.
817 Otherwise @var{base} must have a value between @code{2} and @code{35}.
818 If @var{base} is @code{16}, the digits may optionally be preceded by
819 @samp{0x} or @samp{0X}. If base has no legal value the value returned
820 is @code{0l} and the global variable @code{errno} is set to @code{EINVAL}.
823 Any remaining characters in the string. If @var{tailptr} is not a null
824 pointer, @code{strtol} stores a pointer to this tail in
825 @code{*@var{tailptr}}.
828 If the string is empty, contains only whitespace, or does not contain an
829 initial substring that has the expected syntax for an integer in the
830 specified @var{base}, no conversion is performed. In this case,
831 @code{strtol} returns a value of zero and the value stored in
832 @code{*@var{tailptr}} is the value of @var{string}.
834 In a locale other than the standard @code{"C"} locale, this function
835 may recognize additional implementation-dependent syntax.
837 If the string has valid syntax for an integer but the value is not
838 representable because of overflow, @code{strtol} returns either
839 @code{LONG_MAX} or @code{LONG_MIN} (@pxref{Range of Type}), as
840 appropriate for the sign of the value. It also sets @code{errno}
841 to @code{ERANGE} to indicate there was overflow.
843 Because the value @code{0l} is a correct result for @code{strtol} the
844 user who is interested in handling errors should set the global variable
845 @code{errno} to @code{0} before calling this function, so that the program
846 can later test whether an error occurred.
848 There is an example at the end of this section.
853 @deftypefun {unsigned long int} strtoul (const char *@var{string}, char **@var{tailptr}, int @var{base})
854 The @code{strtoul} (``string-to-unsigned-long'') function is like
855 @code{strtol} except it deals with unsigned numbers, and returns its
856 value with type @code{unsigned long int}. No @samp{+} or @samp{-} sign
857 may appear before the number, but the syntax is otherwise the same as
858 described above for @code{strtol}. The value returned in case of
859 overflow is @code{ULONG_MAX} (@pxref{Range of Type}).
861 Like @code{strtol} this function sets @code{errno} and returns the value
862 @code{0ul} in case the value for @var{base} is not in the legal range.
863 For @code{strtoul} this can happen in another situation. In case the
864 number to be converted is negative @code{strtoul} also sets @code{errno}
865 to @code{EINVAL} and returns @code{0ul}.
870 @deftypefun {long long int} strtoll (const char *@var{string}, char **@var{tailptr}, int @var{base})
871 The @code{strtoll} function is like @code{strtol} except that is deals
872 with extra long numbers and it returns its value with type @code{long
875 If the string has valid syntax for an integer but the value is not
876 representable because of overflow, @code{strtoll} returns either
877 @code{LONG_LONG_MAX} or @code{LONG_LONG_MIN} (@pxref{Range of Type}), as
878 appropriate for the sign of the value. It also sets @code{errno} to
879 @code{ERANGE} to indicate there was overflow.
881 The @code{strtoll} function is a GNU extension but it will eventually be
882 part of the next ISO C standard.
887 @deftypefun {long long int} strtoq (const char *@var{string}, char **@var{tailptr}, int @var{base})
888 @code{strtoq} (``string-to-quad-word'') is only an commonly used other
889 name for the @code{strtoll} function. Everything said for
890 @code{strtoll} applies to @code{strtoq} as well.
895 @deftypefun {unsigned long long int} strtoull (const char *@var{string}, char **@var{tailptr}, int @var{base})
896 The @code{strtoull} function is like @code{strtoul} except that is deals
897 with extra long numbers and it returns its value with type
898 @code{unsigned long long int}. The value returned in case of overflow
899 is @code{ULONG_LONG_MAX} (@pxref{Range of Type}).
901 The @code{strtoull} function is a GNU extension but it will eventually be
902 part of the next ISO C standard.
907 @deftypefun {unsigned long long int} strtouq (const char *@var{string}, char **@var{tailptr}, int @var{base})
908 @code{strtouq} (``string-to-unsigned-quad-word'') is only an commonly
909 used other name for the @code{strtoull} function. Everything said for
910 @code{strtoull} applies to @code{strtouq} as well.
915 @deftypefun {long int} atol (const char *@var{string})
916 This function is similar to the @code{strtol} function with a @var{base}
917 argument of @code{10}, except that it need not detect overflow errors.
918 The @code{atol} function is provided mostly for compatibility with
919 existing code; using @code{strtol} is more robust.
924 @deftypefun int atoi (const char *@var{string})
925 This function is like @code{atol}, except that it returns an @code{int}
926 value rather than @code{long int}. The @code{atoi} function is also
927 considered obsolete; use @code{strtol} instead.
932 @deftypefun {long long int} atoll (const char *@var{string})
933 This function is similar to @code{atol}, except it returns a @code{long
934 long int} value rather than @code{long int}.
936 The @code{atoll} function is a GNU extension but it will eventually be
937 part of the next ISO C standard.
940 The POSIX locales contain some information about how to format numbers
941 (@pxref{General Numeric}). This mainly deals with representing numbers
942 for better readability for humans. The functions present so far in this
943 section cannot handle numbers in this form.
945 If this functionality is needed in a program one can use the functions
946 from the @code{scanf} family which know about the flag @samp{'} for
947 parsing numeric input (@pxref{Numeric Input Conversions}). Sometimes it
948 is more desirable to have finer control.
950 In these situation one could use the function
951 @code{__strto@var{XXX}_internal}. @var{XXX} here stands for any of the
952 above forms. All numeric conversion functions (including the functions
953 to process floating-point numbers) have such a counterpart. The
954 difference to the normal form is the extra argument at the end of the
955 parameter list. If this value has an non-zero value the handling of
956 number grouping is enabled. The advantage of using these functions is
957 that the @var{tailptr} parameters allow to determine which part of the
958 input is processed. The @code{scanf} functions don't provide this
959 information. The drawback of using these functions is that they are not
960 portable. They only exist in the GNU C library.
963 Here is a function which parses a string as a sequence of integers and
964 returns the sum of them:
968 sum_ints_from_string (char *string)
976 /* @r{Skip whitespace by hand, to detect the end.} */
977 while (isspace (*string)) string++;
981 /* @r{There is more nonwhitespace,} */
982 /* @r{so it ought to be another number.} */
985 next = strtol (string, &tail, 0);
986 /* @r{Add it in, if not overflow.} */
988 printf ("Overflow\n");
991 /* @r{Advance past it.} */
999 @node Parsing of Floats
1000 @subsection Parsing of Floats
1003 These functions are declared in @file{stdlib.h}.
1007 @deftypefun double strtod (const char *@var{string}, char **@var{tailptr})
1008 The @code{strtod} (``string-to-double'') function converts the initial
1009 part of @var{string} to a floating-point number, which is returned as a
1010 value of type @code{double}.
1012 This function attempts to decompose @var{string} as follows:
1016 A (possibly empty) sequence of whitespace characters. Which characters
1017 are whitespace is determined by the @code{isspace} function
1018 (@pxref{Classification of Characters}). These are discarded.
1021 An optional plus or minus sign (@samp{+} or @samp{-}).
1024 A nonempty sequence of digits optionally containing a decimal-point
1025 character---normally @samp{.}, but it depends on the locale
1026 (@pxref{Numeric Formatting}).
1029 An optional exponent part, consisting of a character @samp{e} or
1030 @samp{E}, an optional sign, and a sequence of digits.
1033 Any remaining characters in the string. If @var{tailptr} is not a null
1034 pointer, a pointer to this tail of the string is stored in
1035 @code{*@var{tailptr}}.
1038 If the string is empty, contains only whitespace, or does not contain an
1039 initial substring that has the expected syntax for a floating-point
1040 number, no conversion is performed. In this case, @code{strtod} returns
1041 a value of zero and the value returned in @code{*@var{tailptr}} is the
1042 value of @var{string}.
1044 In a locale other than the standard @code{"C"} or @code{"POSIX"} locales,
1045 this function may recognize additional locale-dependent syntax.
1047 If the string has valid syntax for a floating-point number but the value
1048 is not representable because of overflow, @code{strtod} returns either
1049 positive or negative @code{HUGE_VAL} (@pxref{Mathematics}), depending on
1050 the sign of the value. Similarly, if the value is not representable
1051 because of underflow, @code{strtod} returns zero. It also sets @code{errno}
1052 to @code{ERANGE} if there was overflow or underflow.
1054 There are two more special inputs which are recognized by @code{strtod}.
1055 The string @code{"inf"} or @code{"infinity"} (without consideration of
1056 case and optionally preceded by a @code{"+"} or @code{"-"} sign) is
1057 changed to the floating-point value for infinity if the floating-point
1058 format supports this; and to the largest representable value otherwise.
1060 If the input string is @code{"nan"} or
1061 @code{"nan(@var{n-char-sequence})"} the return value of @code{strtod} is
1062 the representation of the NaN (not a number) value (if the
1063 flaoting-point formats supports this. The form with the
1064 @var{n-char-sequence} enables in an implementation specific way to
1065 specify the form of the NaN value. When using the @w{IEEE 754}
1066 floating-point format, the NaN value can have a lot of forms since only
1067 at least one bit in the mantissa must be set. In the GNU C library
1068 implementation of @code{strtod} the @var{n-char-sequence} is interpreted
1069 as a number (as recognized by @code{strtol}, @pxref{Parsing of Integers})
1070 The mantissa of the return value corresponds to this given number.
1072 Since the value zero which is returned in the error case is also a valid
1073 result the user should set the global variable @code{errno} to zero
1074 before calling this function. So one can test for failures after the
1075 call since all failures set @code{errno} to a non-zero value.
1080 @deftypefun float strtof (const char *@var{string}, char **@var{tailptr})
1081 This function is similar to the @code{strtod} function but it returns a
1082 @code{float} value instead of a @code{double} value. If the precision
1083 of a @code{float} value is sufficient this function should be used since
1084 it is much faster than @code{strtod} on some architectures. The reasons
1085 are obvious: @w{IEEE 754} defines @code{float} to have a mantissa of 23
1086 bits while @code{double} has 53 bits and every additional bit of
1087 precision can require additional computation.
1089 If the string has valid syntax for a floating-point number but the value
1090 is not representable because of overflow, @code{strtof} returns either
1091 positive or negative @code{HUGE_VALF} (@pxref{Mathematics}), depending on
1092 the sign of the value.
1094 This function is a GNU extension.
1099 @deftypefun {long double} strtold (const char *@var{string}, char **@var{tailptr})
1100 This function is similar to the @code{strtod} function but it returns a
1101 @code{long double} value instead of a @code{double} value. It should be
1102 used when high precision is needed. On systems which define a @code{long
1103 double} type (i.e., on which it is not the same as @code{double})
1104 running this function might take significantly more time since more bits
1105 of precision are required.
1107 If the string has valid syntax for a floating-point number but the value
1108 is not representable because of overflow, @code{strtold} returns either
1109 positive or negative @code{HUGE_VALL} (@pxref{Mathematics}), depending on
1110 the sign of the value.
1112 This function is a GNU extension.
1115 As for the integer parsing functions there are additional functions
1116 which will handle numbers represented using the grouping scheme of the
1117 current locale (@pxref{Parsing of Integers}).
1121 @deftypefun double atof (const char *@var{string})
1122 This function is similar to the @code{strtod} function, except that it
1123 need not detect overflow and underflow errors. The @code{atof} function
1124 is provided mostly for compatibility with existing code; using
1125 @code{strtod} is more robust.