c-strtof, c-strtod, c-strtold: Make multithread-safe.
[gnulib.git] / doc / intprops.texi
blobbb5fd01ce99ccc7f91444cad03ab3ed6bdf756e0
1 @node Integer Properties
2 @section Integer Properties
4 @c Copyright (C) 2011--2024 Free Software Foundation, Inc.
6 @c Permission is granted to copy, distribute and/or modify this document
7 @c under the terms of the GNU Free Documentation License, Version 1.3 or
8 @c any later version published by the Free Software Foundation; with no
9 @c Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
10 @c copy of the license is at <https://www.gnu.org/licenses/fdl-1.3.en.html>.
12 @c Written by Paul Eggert.
14 @cindex integer properties
16 The @code{intprops} module consists of an include file @code{<intprops.h>}
17 that defines several macros useful for testing properties of integer
18 types.
20 @cindex integer overflow
21 @cindex overflow, integer
23 Integer overflow is a common source of problems in programs written in
24 C and other languages.  In some cases, such as signed integer
25 arithmetic in C programs, the resulting behavior is undefined, and
26 practical platforms do not always behave as if integers wrap around
27 reliably.  In other cases, such as unsigned integer arithmetic in C,
28 the resulting behavior is well-defined, but programs may still
29 misbehave badly after overflow occurs.
31 Many techniques have been proposed to attack these problems.  These
32 include precondition testing, wraparound behavior where signed integer
33 arithmetic is guaranteed to be modular, saturation semantics where
34 overflow reliably yields an extreme value, undefined behavior
35 sanitizers where overflow is guaranteed to trap, and various static
36 analysis techniques.
38 Gnulib supports wraparound arithmetic and precondition testing, as
39 these are relatively easy to support portably and efficiently.  There
40 are two families of precondition tests: the first, for integer types,
41 is easier to use, while the second, for integer ranges, has a simple
42 and straightforward portable implementation.
44 Like other Gnulib modules, the implementation of the @code{intprops}
45 module assumes that integers use a two's complement representation,
46 but it does not assume that signed integer arithmetic wraps around.
47 @xref{Other portability assumptions}.
49 @menu
50 * Arithmetic Type Properties::  Determining properties of arithmetic types.
51 * Integer Bounds::              Bounds on integer values and representations.
52 * Checking Integer Overflow::   Checking for overflow while computing integers.
53 * Wraparound Arithmetic::       Well-defined behavior on integer overflow.
54 * Integer Type Overflow::       General integer overflow checking.
55 * Integer Range Overflow::      Integer overflow checking if bounds are known.
56 @end menu
58 @node Arithmetic Type Properties
59 @subsection Arithmetic Type Properties
61 @findex TYPE_IS_INTEGER
62 @code{TYPE_IS_INTEGER (@var{t})} is an arithmetic constant
63 expression that yields 1 if the arithmetic type @var{t} is an integer type,
64 0 otherwise.
65 @code{bool} counts as an integer type.
67 @findex TYPE_SIGNED
68 @code{TYPE_SIGNED (@var{t})} is an arithmetic constant expression
69 that yields 1 if the real type @var{t} is a signed integer type or a
70 floating type, 0 otherwise.
71 If @var{t} is an integer type, @code{TYPE_SIGNED (@var{t})}
72 is an integer constant expression.
74 @findex EXPR_SIGNED
75 @code{EXPR_SIGNED (@var{e})} yields 1 if the real expression @var{e}
76 has a signed integer type or a floating type, 0 otherwise.  If @var{e} is an
77 integer constant expression or an arithmetic constant expression,
78 @code{EXPR_SIGNED (@var{e})} is likewise.  The expression
79 @var{e} is not evaluated, and @code{EXPR_SIGNED
80 (@var{e})} is typically optimized to a constant.
82 Example usage:
84 @example
85 #include <intprops.h>
86 #include <sys/types.h>
88 enum
90   clock_t_is_integer = TYPE_IS_INTEGER (clock_t),
91   uid_t_is_signed = TYPE_SIGNED (uid_t)
92 @};
94 int
95 CLOCKS_PER_SEC_is_signed (void)
97   return EXPR_SIGNED (CLOCKS_PER_SEC);
99 @end example
101 @node Integer Bounds
102 @subsection Integer Bounds
104 @cindex integer bounds
106 @findex INT_BUFSIZE_BOUND
107 @code{INT_BUFSIZE_BOUND (@var{t})} is an integer constant
108 expression that is a bound on the size of the string representing an
109 integer type or expression @var{t} in decimal notation, including the
110 terminating null character and any leading @code{-} character.  For
111 example, if @code{INT_BUFSIZE_BOUND (int)} is 12, any value of type
112 @code{int} can be represented in 12 bytes or less, including the
113 terminating null.  The bound is not necessarily tight.
115 Example usage:
117 @example
118 #include <intprops.h>
119 #include <stdio.h>
121 int_strlen (int i)
123   char buf[INT_BUFSIZE_BOUND (int)];
124   return sprintf (buf, "%d", i);
126 @end example
128 @findex INT_STRLEN_BOUND
129 @code{INT_STRLEN_BOUND (@var{t})} is an integer constant
130 expression that is a bound on the length of the string representing an
131 integer type or expression @var{t} in decimal notation, including any
132 leading @code{-} character.  This is one less than
133 @code{INT_BUFSIZE_BOUND (@var{t})}.
135 @findex TYPE_MINIMUM
136 @findex TYPE_MAXIMUM
137 @code{TYPE_MINIMUM (@var{t})} and @code{TYPE_MAXIMUM (@var{t})} are
138 integer constant expressions equal to the minimum and maximum
139 values of the integer type @var{t}.  These expressions are of the type
140 @var{t}.
142 Example usage:
144 @example
145 #include <sys/types.h>
146 #include <intprops.h>
147 bool
148 in_off_t_range (long long int a)
150   return TYPE_MINIMUM (off_t) <= a && a <= TYPE_MAXIMUM (off_t);
152 @end example
154 @node Checking Integer Overflow
155 @subsection Checking Integer Overflow
157 @cindex integer overflow checking
159 Signed integer arithmetic has undefined behavior on overflow in C@.
160 Although almost all modern computers use two's complement signed
161 arithmetic that is well-defined to wrap around, C compilers routinely
162 optimize assuming that signed integer overflow cannot occur, which
163 means that a C program cannot easily get at the underlying machine
164 arithmetic.  For example:
166 @example
167 if ((a + b < b) == (a < 0))
168   a += b;
169 else
170   printf ("overflow\n");
171 @end example
173 @noindent
174 might not work as expected if @code{a} and @code{b} are signed,
175 because a compiler can assume that signed overflow cannot occur and
176 treat the entire @code{if} expression as if it were true.  And even if
177 @code{a} is unsigned, the expression might not work as expected if
178 @code{b} is negative or is wider than @code{a}.
180 The following macros work around this problem by yielding an overflow
181 indication while computing the sum, difference, or product of two
182 integers.  For example, if @code{i} is of type @code{int},
183 @code{INT_ADD_OK (INT_MAX - 1, 1, &i)} sets @code{i} to
184 @code{INT_MAX} and yields 1, whereas @code{INT_ADD_OK (INT_MAX, 1,
185 &i)} yields 0.
187 Example usage:
189 @example
190 #include <intprops.h>
191 #include <stdio.h>
193 /* Compute A * B, reporting whether overflow occurred.  */
194 void
195 print_product (long int a, long int b)
197   long int r;
198   if (INT_MULTIPLY_OK (a, b, &r))
199     printf ("result is %ld\n", r);
200   else
201     printf ("overflow\n");
203 @end example
205 These macros work for both signed and unsigned integers, so they can
206 be used with integer types like @code{time_t} that may or may not be
207 signed, depending on the platform.
209 These macros have the following restrictions:
211 @itemize @bullet
212 @item
213 Their first two arguments must be integer expressions.
215 @item
216 Their last argument must be a non-null pointer to an integer.
218 @item
219 They may evaluate their arguments zero or multiple times, so the
220 arguments should not have side effects.
222 @item
223 They are not necessarily constant expressions, even if all their
224 arguments are constant expressions.
225 @end itemize
227 @table @code
228 @item INT_ADD_OK (@var{a}, @var{b}, @var{r})
229 @findex INT_ADD_OK
230 Compute the sum of @var{a} and @var{b}.  If it fits into
231 @code{*@var{r}}, store it there and yield 1.  Otherwise yield
232 0, possibly modifying @code{*@var{r}} to an unspecified value.
233 See above for restrictions.
235 @item INT_SUBTRACT_OK (@var{a}, @var{b}, @var{r})
236 @findex INT_SUBTRACT_OK
237 Compute the difference between @var{a} and @var{b}.  If it fits into
238 @code{*@var{r}}, store it there and yield 1.  Otherwise yield
239 0, possibly modifying @code{*@var{r}} to an unspecified value.
240 See above for restrictions.
242 @item INT_MULTIPLY_OK (@var{a}, @var{b}, @var{r})
243 @findex INT_MULTIPLY_OK
244 Compute the product of @var{a} and @var{b}.  If it fits into
245 @code{*@var{r}}, store it there and yield 1.  Otherwise yield
246 0, possibly modifying @code{*@var{r}} to an unspecified value.
247 See above for restrictions.
248 @end table
250 Other macros are available if you need wrapped-around results when
251 overflow occurs (@pxref{Wraparound Arithmetic}), or if you need to
252 check for overflow in operations other than addition, subtraction, and
253 multiplication (@pxref{Integer Type Overflow}).
255 @node Wraparound Arithmetic
256 @subsection Wraparound Arithmetic with Integers
258 @cindex wraparound integer arithmetic
260 Signed integer arithmetic has undefined behavior on overflow in C@.
261 Although almost all modern computers use two's complement signed
262 arithmetic that is well-defined to wrap around, C compilers routinely
263 optimize assuming that signed integer overflow cannot occur, which
264 means that a C program cannot easily get at the underlying machine
265 arithmetic.  For example, on a typical machine with 32-bit two's
266 complement @code{int} the expression @code{INT_MAX + 1} does not
267 necessarily yield @code{INT_MIN}, because the compiler may do
268 calculations with a 64-bit register, or may generate code that
269 traps on signed integer overflow.
271 The following macros work around this problem by storing the
272 wraparound value, i.e., the low-order bits of the correct answer, and
273 by yielding an overflow indication.  For example, if @code{i} is of
274 type @code{int}, @code{INT_ADD_WRAPV (INT_MAX, 1, &i)} sets @code{i}
275 to @code{INT_MIN} and yields 1 on a two's complement machine.
276 @xref{Integer Type Overflow}.
278 Example usage:
280 @example
281 #include <intprops.h>
282 #include <stdio.h>
284 /* Print the low order bits of A * B,
285    reporting whether overflow occurred.  */
286 void
287 print_product (long int a, long int b)
289   long int r;
290   int overflow = INT_MULTIPLY_WRAPV (a, b, &r);
291   printf ("result is %ld (%s)\n", r,
292           (overflow
293            ? "after overflow"
294            : "no overflow"));
296 @end example
298 These macros work for both signed and unsigned integers, so they can
299 be used with integer types like @code{time_t} that may or may not be
300 signed, depending on the platform.
302 These macros have the following restrictions:
304 @itemize @bullet
305 @item
306 Their first two arguments must be integer expressions.
308 @item
309 Their last argument must be a non-null pointer to an integer.
311 @item
312 They may evaluate their arguments zero or multiple times, so the
313 arguments should not have side effects.
315 @item
316 They are not necessarily constant expressions, even if all their
317 arguments are constant expressions.
318 @end itemize
320 @table @code
321 @item INT_ADD_WRAPV (@var{a}, @var{b}, @var{r})
322 @findex INT_ADD_WRAPV
323 Store the low-order bits of the sum of @var{a} and @var{b} into
324 @code{*@var{r}}.  Yield 1 if overflow occurred, 0 if the
325 low-order bits are the mathematically-correct sum.  See above for
326 restrictions.
328 @item INT_SUBTRACT_WRAPV (@var{a}, @var{b}, @var{r})
329 @findex INT_SUBTRACT_WRAPV
330 Store the low-order bits of the difference between @var{a} and @var{b}
331 into @code{*@var{r}}.  Yield 1 if overflow occurred, 0 if the
332 low-order bits are the mathematically-correct difference.  See above
333 for restrictions.
335 @item INT_MULTIPLY_WRAPV (@var{a}, @var{b}, @var{r})
336 @findex INT_MULTIPLY_WRAPV
337 Store the low-order bits of the product of @var{a} and @var{b} into
338 @code{*@var{r}}.  Yield 1 if overflow occurred, 0 if the
339 low-order bits are the mathematically-correct product.  See above for
340 restrictions.
341 @end table
343 If your code includes @code{<intprops.h>} only for these @code{_WRAPV}
344 macros, you may prefer to use Gnulib's @code{stdckdint} module
345 instead, as it supports similar macros that were standardized in C23
346 and are therefore independent of Gnulib if your code can assume C23 or
347 later.  @xref{stdckdint.h}.
349 Other macros are available if you do not need wrapped-around results
350 when overflow occurs (@pxref{Checking Integer Overflow}), or if you
351 need to check for overflow in operations other than addition,
352 subtraction, and multiplication (@pxref{Integer Type Overflow}).
354 @node Integer Type Overflow
355 @subsection Integer Type Overflow
357 @cindex integer type overflow
358 @cindex overflow, integer type
360 Although unsigned integer arithmetic wraps around modulo a power of
361 two, signed integer arithmetic has undefined behavior on overflow in
362 C@.  Almost all modern computers use two's complement signed
363 arithmetic that is well-defined to wrap around, but C compilers
364 routinely optimize based on the assumption that signed integer
365 overflow cannot occur, which means that a C program cannot easily get
366 at the underlying machine behavior.  For example, the signed integer
367 expression @code{(a + b < b) != (a < 0)} is not a reliable test for
368 whether @code{a + b} overflows, because a compiler can assume that
369 signed overflow cannot occur and treat the entire expression as if it
370 were false.
372 These macros yield 1 if the corresponding C operators overflow, 0 otherwise.
373 They work correctly on all known practical hosts, and do not
374 rely on undefined behavior due to signed arithmetic overflow.  They
375 are integer constant expressions if their arguments are.  They
376 are typically easier to use than the integer range overflow macros
377 (@pxref{Integer Range Overflow}), and they support more operations and
378 evaluation contexts than the integer overflow checking macros
379 (@pxref{Checking Integer Overflow}) or the wraparound macros
380 (@pxref{Wraparound Arithmetic}).
382 These macros can be tricky to use with arguments narrower than
383 @code{int}.  For example, in the common case with 16-bit @code{short
384 int} and 32-bit @code{int}, if @code{a} and @code{b} are of type
385 @code{short int} then @code{INT_MULTIPLY_OVERFLOW (a, b)} always
386 yields 0, as @code{a * b} cannot overflow due to C's rule that
387 @code{a} and @code{b} are widened to @code{int} before multiplying.
388 For this reason, often it is better to use the integer overflow
389 checking macros (@pxref{Checking Integer Overflow}) or the wraparound
390 macros (@pxref{Wraparound Arithmetic}) when checking for overflow in
391 addition, subtraction, or multiplication.
393 Example usage:
395 @example
396 #include <intprops.h>
397 #include <limits.h>
398 #include <stdio.h>
400 /* Print A * B if in range, an overflow
401    indicator otherwise.  */
402 void
403 print_product (long int a, long int b)
405   if (INT_MULTIPLY_OVERFLOW (a, b))
406     printf ("multiply would overflow");
407   else
408     printf ("product is %ld", a * b);
411 /* Does the product of two ints always fit
412    in a long int?  */
413 enum @{
414   INT_PRODUCTS_FIT_IN_LONG
415     = ! (INT_MULTIPLY_OVERFLOW
416          ((long int) INT_MIN, INT_MIN))
418 @end example
420 @noindent
421 These macros have the following restrictions:
423 @itemize @bullet
424 @item
425 Their arguments must be integer expressions.
427 @item
428 They may evaluate their arguments zero or multiple times, so the
429 arguments should not have side effects.
430 @end itemize
432 @noindent
433 These macros are tuned for their last argument being a constant.
435 @table @code
436 @item INT_ADD_OVERFLOW (@var{a}, @var{b})
437 @findex INT_ADD_OVERFLOW
438 Yield 1 if @code{@var{a} + @var{b}} would overflow, 0 otherwise.  See above for
439 restrictions.
441 @item INT_SUBTRACT_OVERFLOW (@var{a}, @var{b})
442 @findex INT_SUBTRACT_OVERFLOW
443 Yield 1 if @code{@var{a} - @var{b}} would overflow, 0 otherwise.  See above for
444 restrictions.
446 @item INT_NEGATE_OVERFLOW (@var{a})
447 @findex INT_NEGATE_OVERFLOW
448 Yields 1 if @code{-@var{a}} would overflow, 0 otherwise.
449 See above for restrictions.
451 @item INT_MULTIPLY_OVERFLOW (@var{a}, @var{b})
452 @findex INT_MULTIPLY_OVERFLOW
453 Yield 1 if @code{@var{a} * @var{b}} would overflow, 0 otherwise.  See above for
454 restrictions.
456 @item INT_DIVIDE_OVERFLOW (@var{a}, @var{b})
457 @findex INT_DIVIDE_OVERFLOW
458 Yield 1 if @code{@var{a} / @var{b}} would overflow, 0 otherwise.  See above for
459 restrictions.  Division overflow can happen on two's complement hosts
460 when dividing the most negative integer by @minus{}1.  This macro does
461 not check for division by zero.
463 @item INT_REMAINDER_OVERFLOW (@var{a}, @var{b})
464 @findex INT_REMAINDER_OVERFLOW
465 Yield 1 if @code{@var{a} % @var{b}} would overflow, 0 otherwise.  See above for
466 restrictions.  Remainder overflow can happen on two's complement hosts
467 when dividing the most negative integer by @minus{}1; although the
468 mathematical result is always 0, in practice some implementations
469 trap, so this counts as an overflow.  This macro does not check for
470 division by zero.
472 @item INT_LEFT_SHIFT_OVERFLOW (@var{a}, @var{b})
473 @findex INT_LEFT_SHIFT_OVERFLOW
474 Yield 1 if @code{@var{a} << @var{b}} would overflow, 0 otherwise.  See above for
475 restrictions.  The C standard says that behavior is undefined for
476 shifts unless 0@leq{}@var{b}<@var{w} where @var{w} is @var{a}'s word
477 width, and that when @var{a} is negative then @code{@var{a} <<
478 @var{b}} has undefined behavior, but this macro does not check these
479 other restrictions.
480 @end table
482 @node Integer Range Overflow
483 @subsection Integer Range Overflow
485 @cindex integer range overflow
486 @cindex overflow, integer range
488 These macros yield 1 if the corresponding C operators might not yield
489 numerically correct answers due to arithmetic overflow, and 0 if if
490 the operators do not overflow.  They do not
491 rely on undefined or implementation-defined behavior.  They are
492 integer constant expressions if their arguments are.  Their
493 implementations are simple and straightforward, but they are typically
494 harder to use than the integer type overflow macros.  @xref{Integer
495 Type Overflow}.
497 Although the implementation of these macros is similar to that
498 suggested in the SEI CERT C Secure Coding Standard,
499 in its two sections
500 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap,
501 INT30-C@. Ensure that unsigned integer operations do not wrap}'' and
502 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow,
503 INT32-C@. Ensure that operations on signed integers do not result in
504 overflow}'', Gnulib's implementation was derived independently of
505 CERT's suggestions.
507 Example usage:
509 @example
510 #include <intprops.h>
511 #include <limits.h>
512 #include <stdio.h>
514 void
515 print_product (long int a, long int b)
517   if (INT_MULTIPLY_RANGE_OVERFLOW (a, b, LONG_MIN, LONG_MAX))
518     printf ("multiply would overflow");
519   else
520     printf ("product is %ld", a * b);
523 /* Does the product of two ints always fit
524    in a long int?  */
525 enum @{
526   INT_PRODUCTS_FIT_IN_LONG
527     = ! (INT_MULTIPLY_RANGE_OVERFLOW
528          ((long int) INT_MIN, (long int) INT_MIN,
529           LONG_MIN, LONG_MAX))
531 @end example
533 @noindent
534 These macros have the following restrictions:
536 @itemize @bullet
537 @item
538 Their arguments must be integer expressions.
540 @item
541 They may evaluate their arguments zero or multiple times, so
542 the arguments should not have side effects.
544 @item
545 The arithmetic arguments (including the @var{min} and @var{max}
546 arguments) must be of the same integer type after the usual arithmetic
547 conversions, and the type must have minimum value @var{min} and
548 maximum @var{max}.  Unsigned values should use a zero @var{min} of the
549 proper type, for example, @code{(unsigned int) 0}.
550 @end itemize
552 @noindent
553 These macros are tuned for constant @var{min} and @var{max}.  For
554 commutative operations such as @code{@var{a} + @var{b}}, they are also
555 tuned for constant @var{b}.
557 @table @code
558 @item INT_ADD_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
559 @findex INT_ADD_RANGE_OVERFLOW
560 Yield 1 if @code{@var{a} + @var{b}} would overflow in
561 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
562 See above for restrictions.
564 @item INT_SUBTRACT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
565 @findex INT_SUBTRACT_RANGE_OVERFLOW
566 Yield 1 if @code{@var{a} - @var{b}} would overflow in
567 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
568 See above for restrictions.
570 @item INT_NEGATE_RANGE_OVERFLOW (@var{a}, @var{min}, @var{max})
571 @findex INT_NEGATE_RANGE_OVERFLOW
572 Yield 1 if @code{-@var{a}} would overflow in [@var{min},@var{max}]
573 integer arithmetic, 0 otherwise.  See above for restrictions.
575 @item INT_MULTIPLY_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
576 @findex INT_MULTIPLY_RANGE_OVERFLOW
577 Yield 1 if @code{@var{a} * @var{b}} would overflow in
578 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
579 See above for restrictions.
581 @item INT_DIVIDE_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
582 @findex INT_DIVIDE_RANGE_OVERFLOW
583 Yield 1 if @code{@var{a} / @var{b}} would overflow in
584 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
585 See above for restrictions.
586 Division overflow can happen on two's complement hosts when dividing
587 the most negative integer by @minus{}1.  This macro does not check for
588 division by zero.
590 @item INT_REMAINDER_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
591 @findex INT_REMAINDER_RANGE_OVERFLOW
592 Yield 1 if @code{@var{a} % @var{b}} would overflow in
593 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
594 See above for restrictions.
595 Remainder overflow can happen on two's complement hosts when dividing
596 the most negative integer by @minus{}1; although the mathematical
597 result is always 0, in practice some implementations trap, so this
598 counts as an overflow.  This macro does not check for division by
599 zero.
601 @item INT_LEFT_SHIFT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
602 @findex INT_LEFT_SHIFT_RANGE_OVERFLOW
603 Yield 1 if @code{@var{a} << @var{b}} would overflow in
604 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
605 See above for restrictions.
606 Here, @var{min} and @var{max} are for @var{a} only, and @var{b} need
607 not be of the same type as the other arguments.  The C standard says
608 that behavior is undefined for shifts unless 0@leq{}@var{b}<@var{w}
609 where @var{w} is @var{a}'s word width, and that when @var{a} is negative
610 then @code{@var{a} << @var{b}} has undefined behavior, but this macro
611 does not check these other restrictions.
612 @end table