1 @node Integer Properties
2 @section Integer Properties
4 @c Copyright (C) 2011--2021 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
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
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}.
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.
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 is 1 if the arithmetic type @var{t} is an integer type.
64 @code{_Bool} counts as an integer type.
67 @code{TYPE_SIGNED (@var{t})} is an arithmetic constant expression
68 that is 1 if the real type @var{t} is a signed integer type or a
69 floating type. If @var{t} is an integer type, @code{TYPE_SIGNED (@var{t})}
70 is an integer constant expression.
73 @code{EXPR_SIGNED (@var{e})} is 1 if the real expression @var{e}
74 has a signed integer type or a floating type. If @var{e} is an
75 integer constant expression or an arithmetic constant expression,
76 @code{EXPR_SIGNED (@var{e})} is likewise. The expression
77 @var{e} is not evaluated, and @code{EXPR_SIGNED
78 (@var{e})} is typically optimized to a constant.
88 time_t_is_signed_integer =
89 TYPE_IS_INTEGER (time_t) && TYPE_SIGNED (time_t)
93 CLOCKS_PER_SEC_is_signed (void)
95 return EXPR_SIGNED (CLOCKS_PER_SEC);
100 @subsection Integer Bounds
102 @cindex integer bounds
104 @findex INT_BUFSIZE_BOUND
105 @code{INT_BUFSIZE_BOUND (@var{t})} is an integer constant
106 expression that is a bound on the size of the string representing an
107 integer type or expression @var{t} in decimal notation, including the
108 terminating null character and any leading @code{-} character. For
109 example, if @code{INT_BUFSIZE_BOUND (int)} is 12, any value of type
110 @code{int} can be represented in 12 bytes or less, including the
111 terminating null. The bound is not necessarily tight.
116 #include <intprops.h>
121 char buf[INT_BUFSIZE_BOUND (int)];
122 return sprintf (buf, "%d", i);
126 @findex INT_STRLEN_BOUND
127 @code{INT_STRLEN_BOUND (@var{t})} is an integer constant
128 expression that is a bound on the length of the string representing an
129 integer type or expression @var{t} in decimal notation, including any
130 leading @code{-} character. This is one less than
131 @code{INT_BUFSIZE_BOUND (@var{t})}.
135 @code{TYPE_MINIMUM (@var{t})} and @code{TYPE_MAXIMUM (@var{t})} are
136 integer constant expressions equal to the minimum and maximum
137 values of the integer type @var{t}. These expressions are of the type
138 @var{t} (or more precisely, the type @var{t} after integer
145 #include <sys/types.h>
146 #include <intprops.h>
148 in_off_t_range (intmax_t a)
150 return TYPE_MINIMUM (off_t) <= a && a <= TYPE_MAXIMUM (off_t);
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:
167 if ((a + b < b) == (a < 0))
170 printf ("overflow\n");
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 returning 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 returns true, whereas @code{INT_ADD_OK (INT_MAX, 1,
190 #include <intprops.h>
193 /* Compute A * B, reporting whether overflow occurred. */
195 print_product (long int a, long int b)
198 if (INT_MULTIPLY_OK (a, b, r))
199 printf ("result is %ld\n", r);
201 printf ("overflow\n");
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:
213 Their first two arguments must be integer expressions.
216 Their last argument must be a non-null pointer to an integer.
219 They may evaluate their arguments zero or multiple times, so the
220 arguments should not have side effects.
223 They are not necessarily constant expressions, even if all their
224 arguments are constant expressions.
228 @item INT_ADD_OK (@var{a}, @var{b}, @var{r})
230 Compute the sum of @var{a} and @var{b}. If it fits into
231 @code{*@var{r}}, store it there and return true. Otherwise return
232 false, 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 return true. Otherwise return
239 false, 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 return true. Otherwise return
246 false, possibly modifying @code{*@var{r}} to an unspecified value.
247 See above for restrictions.
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 returning 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 returns 1 on a two's complement machine.
276 @xref{Integer Type Overflow}.
281 #include <intprops.h>
284 /* Print the low order bits of A * B,
285 reporting whether overflow occurred. */
287 print_product (long int a, long int b)
290 int overflow = INT_MULTIPLY_WRAPV (a, b, &r);
291 printf ("result is %ld (%s)\n", r,
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:
306 Their first two arguments must be integer expressions.
309 Their last argument must be a non-null pointer to an integer.
312 They may evaluate their arguments zero or multiple times, so the
313 arguments should not have side effects.
316 They are not necessarily constant expressions, even if all their
317 arguments are constant expressions.
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}}. Return true if overflow occurred, false if the
325 low-order bits are the mathematically-correct sum. See above for
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}}. Return true if overflow occurred, false if the
332 low-order bits are the mathematically-correct difference. See above
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}}. Return true if overflow occurred, false if the
339 low-order bits are the mathematically-correct product. See above for
343 Other macros are available if you do not need wrapped-around results
344 when overflow occurs (@pxref{Checking Integer Overflow}), or if you
345 need to check for overflow in operations other than addition,
346 subtraction, and multiplication (@pxref{Integer Type Overflow}).
348 @node Integer Type Overflow
349 @subsection Integer Type Overflow
351 @cindex integer type overflow
352 @cindex overflow, integer type
354 Although unsigned integer arithmetic wraps around modulo a power of
355 two, signed integer arithmetic has undefined behavior on overflow in
356 C@. Almost all modern computers use two's complement signed
357 arithmetic that is well-defined to wrap around, but C compilers
358 routinely optimize based on the assumption that signed integer
359 overflow cannot occur, which means that a C program cannot easily get
360 at the underlying machine behavior. For example, the signed integer
361 expression @code{(a + b < b) != (a < 0)} is not a reliable test for
362 whether @code{a + b} overflows, because a compiler can assume that
363 signed overflow cannot occur and treat the entire expression as if it
366 These macros yield 1 if the corresponding C operators might not yield
367 numerically correct answers due to arithmetic overflow of an integer
368 type. They work correctly on all known practical hosts, and do not
369 rely on undefined behavior due to signed arithmetic overflow. They
370 are integer constant expressions if their arguments are. They
371 are typically easier to use than the integer range overflow macros
372 (@pxref{Integer Range Overflow}), and they support more operations and
373 evaluation contexts than the wraparound macros (@pxref{Wraparound
379 #include <intprops.h>
383 /* Print A * B if in range, an overflow
384 indicator otherwise. */
386 print_product (long int a, long int b)
388 if (INT_MULTIPLY_OVERFLOW (a, b))
389 printf ("multiply would overflow");
391 printf ("product is %ld", a * b);
394 /* Does the product of two ints always fit
397 INT_PRODUCTS_FIT_IN_LONG
398 = ! (INT_MULTIPLY_OVERFLOW
399 ((long int) INT_MIN, INT_MIN))
404 These macros have the following restrictions:
408 Their arguments must be integer expressions.
411 They may evaluate their arguments zero or multiple times, so the
412 arguments should not have side effects.
416 These macros are tuned for their last argument being a constant.
419 @item INT_ADD_OVERFLOW (@var{a}, @var{b})
420 @findex INT_ADD_OVERFLOW
421 Yield 1 if @code{@var{a} + @var{b}} would overflow. See above for
424 @item INT_SUBTRACT_OVERFLOW (@var{a}, @var{b})
425 @findex INT_SUBTRACT_OVERFLOW
426 Yield 1 if @code{@var{a} - @var{b}} would overflow. See above for
429 @item INT_NEGATE_OVERFLOW (@var{a})
430 @findex INT_NEGATE_OVERFLOW
431 Yields 1 if @code{-@var{a}} would overflow. See above for restrictions.
433 @item INT_MULTIPLY_OVERFLOW (@var{a}, @var{b})
434 @findex INT_MULTIPLY_OVERFLOW
435 Yield 1 if @code{@var{a} * @var{b}} would overflow. See above for
438 @item INT_DIVIDE_OVERFLOW (@var{a}, @var{b})
439 @findex INT_DIVIDE_OVERFLOW
440 Yields 1 if @code{@var{a} / @var{b}} would overflow. See above for
441 restrictions. Division overflow can happen on two's complement hosts
442 when dividing the most negative integer by @minus{}1. This macro does
443 not check for division by zero.
445 @item INT_REMAINDER_OVERFLOW (@var{a}, @var{b})
446 @findex INT_REMAINDER_OVERFLOW
447 Yield 1 if @code{@var{a} % @var{b}} would overflow. See above for
448 restrictions. Remainder overflow can happen on two's complement hosts
449 when dividing the most negative integer by @minus{}1; although the
450 mathematical result is always 0, in practice some implementations
451 trap, so this counts as an overflow. This macro does not check for
454 @item INT_LEFT_SHIFT_OVERFLOW (@var{a}, @var{b})
455 @findex INT_LEFT_SHIFT_OVERFLOW
456 Yield 1 if @code{@var{a} << @var{b}} would overflow. See above for
457 restrictions. The C standard says that behavior is undefined for
458 shifts unless 0@leq{}@var{b}<@var{w} where @var{w} is @var{a}'s word
459 width, and that when @var{a} is negative then @code{@var{a} <<
460 @var{b}} has undefined behavior, but this macro does not check these
464 @node Integer Range Overflow
465 @subsection Integer Range Overflow
467 @cindex integer range overflow
468 @cindex overflow, integer range
470 These macros yield 1 if the corresponding C operators might not yield
471 numerically correct answers due to arithmetic overflow. They do not
472 rely on undefined or implementation-defined behavior. They are
473 integer constant expressions if their arguments are. Their
474 implementations are simple and straightforward, but they are typically
475 harder to use than the integer type overflow macros. @xref{Integer
478 Although the implementation of these macros is similar to that
479 suggested in the SEI CERT C Secure Coding Standard,
481 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap,
482 INT30-C@. Ensure that unsigned integer operations do not wrap}'' and
483 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow,
484 INT32-C@. Ensure that operations on signed integers do not result in
485 overflow}'', Gnulib's implementation was derived independently of
491 #include <intprops.h>
496 print_product (long int a, long int b)
498 if (INT_MULTIPLY_RANGE_OVERFLOW (a, b, LONG_MIN, LONG_MAX))
499 printf ("multiply would overflow");
501 printf ("product is %ld", a * b);
504 /* Does the product of two ints always fit
507 INT_PRODUCTS_FIT_IN_LONG
508 = ! (INT_MULTIPLY_RANGE_OVERFLOW
509 ((long int) INT_MIN, (long int) INT_MIN,
515 These macros have the following restrictions:
519 Their arguments must be integer expressions.
522 They may evaluate their arguments zero or multiple times, so
523 the arguments should not have side effects.
526 The arithmetic arguments (including the @var{min} and @var{max}
527 arguments) must be of the same integer type after the usual arithmetic
528 conversions, and the type must have minimum value @var{min} and
529 maximum @var{max}. Unsigned values should use a zero @var{min} of the
530 proper type, for example, @code{(unsigned int) 0}.
534 These macros are tuned for constant @var{min} and @var{max}. For
535 commutative operations such as @code{@var{a} + @var{b}}, they are also
536 tuned for constant @var{b}.
539 @item INT_ADD_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
540 @findex INT_ADD_RANGE_OVERFLOW
541 Yield 1 if @code{@var{a} + @var{b}} would overflow in
542 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
544 @item INT_SUBTRACT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
545 @findex INT_SUBTRACT_RANGE_OVERFLOW
546 Yield 1 if @code{@var{a} - @var{b}} would overflow in
547 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
549 @item INT_NEGATE_RANGE_OVERFLOW (@var{a}, @var{min}, @var{max})
550 @findex INT_NEGATE_RANGE_OVERFLOW
551 Yield 1 if @code{-@var{a}} would overflow in [@var{min},@var{max}]
552 integer arithmetic. See above for restrictions.
554 @item INT_MULTIPLY_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
555 @findex INT_MULTIPLY_RANGE_OVERFLOW
556 Yield 1 if @code{@var{a} * @var{b}} would overflow in
557 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
559 @item INT_DIVIDE_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
560 @findex INT_DIVIDE_RANGE_OVERFLOW
561 Yield 1 if @code{@var{a} / @var{b}} would overflow in
562 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
563 Division overflow can happen on two's complement hosts when dividing
564 the most negative integer by @minus{}1. This macro does not check for
567 @item INT_REMAINDER_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
568 @findex INT_REMAINDER_RANGE_OVERFLOW
569 Yield 1 if @code{@var{a} % @var{b}} would overflow in
570 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
571 Remainder overflow can happen on two's complement hosts when dividing
572 the most negative integer by @minus{}1; although the mathematical
573 result is always 0, in practice some implementations trap, so this
574 counts as an overflow. This macro does not check for division by
577 @item INT_LEFT_SHIFT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
578 @findex INT_LEFT_SHIFT_RANGE_OVERFLOW
579 Yield 1 if @code{@var{a} << @var{b}} would overflow in
580 [@var{min},@var{max}] integer arithmetic. See above for restrictions.
581 Here, @var{min} and @var{max} are for @var{a} only, and @var{b} need
582 not be of the same type as the other arguments. The C standard says
583 that behavior is undefined for shifts unless 0@leq{}@var{b}<@var{w}
584 where @var{w} is @var{a}'s word width, and that when @var{a} is negative
585 then @code{@var{a} << @var{b}} has undefined behavior, but this macro
586 does not check these other restrictions.