1 @node Integer Properties
2 @section Integer Properties
4 @c Copyright (C) 2011--2025 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
17 The @code{intprops} module consists of an include file @code{<intprops.h>}
18 that defines several macros useful for testing properties of integer
21 @cindex integer overflow
22 @cindex overflow, integer
24 Integer overflow is a common source of problems in programs written in
25 C and other languages. In some cases, such as signed integer
26 arithmetic in C programs, the resulting behavior is undefined, and
27 practical platforms do not always behave as if integers wrap around
28 reliably. In other cases, such as unsigned integer arithmetic in C,
29 the resulting behavior is well-defined, but programs may still
30 misbehave badly after overflow occurs.
32 Many techniques have been proposed to attack these problems. These
33 include precondition testing, wraparound behavior where signed integer
34 arithmetic is guaranteed to be modular, saturation semantics where
35 overflow reliably yields an extreme value, undefined behavior
36 sanitizers where overflow is guaranteed to trap, and various static
39 Gnulib supports wraparound arithmetic and precondition testing, as
40 these are relatively easy to support portably and efficiently. There
41 are two families of precondition tests: the first, for integer types,
42 is easier to use, while the second, for integer ranges, has a simple
43 and straightforward portable implementation.
45 Like other Gnulib modules, the implementation of the @code{intprops}
46 module assumes that integers use a two's complement representation,
47 but it does not assume that signed integer arithmetic wraps around.
48 @xref{Other portability assumptions}.
51 * Arithmetic Type Properties:: Determining properties of arithmetic types.
52 * Arithmetic Type Conversion:: Converting arithmetic types.
53 * Integer Bounds:: Bounds on integer values and representations.
54 * Checking Integer Overflow:: Checking for overflow while computing integers.
55 * Wraparound Arithmetic:: Well-defined behavior on integer overflow.
56 * Integer Type Overflow:: General integer overflow checking.
57 * Integer Range Overflow:: Integer overflow checking if bounds are known.
60 @node Arithmetic Type Properties
61 @subsection Arithmetic Type Properties
63 @findex TYPE_IS_INTEGER
64 @code{TYPE_IS_INTEGER (@var{t})} is an arithmetic constant
65 expression that yields 1 if the arithmetic type @var{t} is an integer type,
67 @code{bool} counts as an integer type.
70 @code{TYPE_SIGNED (@var{t})} is an arithmetic constant expression
71 that yields 1 if the real type @var{t} is a signed integer type or a
72 floating type, 0 otherwise.
73 If @var{t} is an integer type, @code{TYPE_SIGNED (@var{t})}
74 is an integer constant expression.
77 @code{EXPR_SIGNED (@var{e})} yields 1 if the real expression @var{e}
78 has a signed integer type or a floating type, 0 otherwise. If @var{e} is an
79 integer constant expression or an arithmetic constant expression,
80 @code{EXPR_SIGNED (@var{e})} is likewise. The expression
81 @var{e} is not evaluated, and @code{EXPR_SIGNED
82 (@var{e})} is typically optimized to a constant.
88 #include <sys/types.h>
92 clock_t_is_integer = TYPE_IS_INTEGER (clock_t),
93 uid_t_is_signed = TYPE_SIGNED (uid_t)
97 CLOCKS_PER_SEC_is_signed (void)
99 return EXPR_SIGNED (CLOCKS_PER_SEC);
103 @node Arithmetic Type Conversion
104 @subsection Arithmetic Type Conversion
106 @cindex type conversion, arithmetic
107 @cindex arithmetic type conversion
108 @cindex integer type conversion
110 Here are some ways in C to convert an arithmetic expression @var{e} to
111 a possibly different arithmetic type @var{t}.
115 An explicit conversion like @code{((@var{t}) @var{e})} is powerful and
116 can therefore be dangerous, because the conversion can succeed even if
117 neither @var{e} nor @var{t} happens to have an arithmetic type. For
118 example, if @var{e} is a pointer, @code{((long int) @var{e})} will do
119 a conversion even if that was not the intent.
122 An implicit conversion like @code{@var{t} v = @var{e};} is less
123 powerful, as it does not convert from pointers. However, it can lose
124 information and sign, as in for example @code{int v = -0.9;} which
125 sets @code{v} to zero.
128 A no-op arithmetic expression like @code{+@var{e}} is even less
129 powerful, as it preserves value (including sign) because it does only
130 integer promotions. That is, it converts to @code{int} if that can
131 represent all values of @code{e}'s underlying type, otherwise to
132 @code{unsigned int} if that can represent all values, and
133 otherwise it does no conversion.
137 @code{INT_PROMOTE (@var{e})} is an expression with the same value as
138 the arithmetic expression @var{e} but with @var{e}'s type after
139 any integer promotion. It behaves like @code{+@var{e}}.
141 In the following example, using @code{INT_PROMOTE} pacifies GCC's
142 @code{-Wswitch-enum} option, and may help human readers see what is
143 going on even if they are not expert in C's integer promotion rules
144 and might be confused by the simpler @code{switch (+v)}.
147 enum @{ A = 1, B, C, D, E @} v = ...;
148 switch (INT_PROMOTE (v))
153 /* Handle all other cases,
154 even cases like v == 0. */
160 @subsection Integer Bounds
162 @cindex integer bounds
164 @findex INT_BUFSIZE_BOUND
165 @code{INT_BUFSIZE_BOUND (@var{t})} is an integer constant
166 expression that is a bound on the size of the string representing an
167 integer type or expression @var{t} in decimal notation, including the
168 terminating null character and any leading @code{-} character. For
169 example, if @code{INT_BUFSIZE_BOUND (int)} is 12, any value of type
170 @code{int} can be represented in 12 bytes or less, including the
171 terminating null. The bound is not necessarily tight.
176 #include <intprops.h>
181 char buf[INT_BUFSIZE_BOUND (int)];
182 return sprintf (buf, "%d", i);
186 @findex INT_STRLEN_BOUND
187 @code{INT_STRLEN_BOUND (@var{t})} is an integer constant
188 expression that is a bound on the length of the string representing an
189 integer type or expression @var{t} in decimal notation, including any
190 leading @code{-} character. This is one less than
191 @code{INT_BUFSIZE_BOUND (@var{t})}.
195 @code{TYPE_MINIMUM (@var{t})} and @code{TYPE_MAXIMUM (@var{t})} are
196 integer constant expressions equal to the minimum and maximum
197 values of the integer type @var{t}. These expressions are of the type
203 #include <sys/types.h>
204 #include <intprops.h>
206 in_off_t_range (long long int a)
208 return TYPE_MINIMUM (off_t) <= a && a <= TYPE_MAXIMUM (off_t);
212 @node Checking Integer Overflow
213 @subsection Checking Integer Overflow
215 @cindex integer overflow checking
217 Signed integer arithmetic has undefined behavior on overflow in C@.
218 Although almost all modern computers use two's complement signed
219 arithmetic that is well-defined to wrap around, C compilers routinely
220 optimize assuming that signed integer overflow cannot occur, which
221 means that a C program cannot easily get at the underlying machine
222 arithmetic. For example:
225 if ((a + b < b) == (a < 0))
228 printf ("overflow\n");
232 might not work as expected if @code{a} and @code{b} are signed,
233 because a compiler can assume that signed overflow cannot occur and
234 treat the entire @code{if} expression as if it were true. And even if
235 @code{a} is unsigned, the expression might not work as expected if
236 @code{b} is negative or is wider than @code{a}.
238 The following macros work around this problem by yielding an overflow
239 indication while computing the sum, difference, or product of two
240 integers. For example, if @code{i} is of type @code{int},
241 @code{INT_ADD_OK (INT_MAX - 1, 1, &i)} sets @code{i} to
242 @code{INT_MAX} and yields 1, whereas @code{INT_ADD_OK (INT_MAX, 1,
248 #include <intprops.h>
251 /* Compute A * B, reporting whether overflow occurred. */
253 print_product (long int a, long int b)
256 if (INT_MULTIPLY_OK (a, b, &r))
257 printf ("result is %ld\n", r);
259 printf ("overflow\n");
263 These macros work for both signed and unsigned integers, so they can
264 be used with integer types like @code{time_t} that may or may not be
265 signed, depending on the platform.
267 These macros have the following restrictions:
271 Their first two arguments must be integer expressions.
274 Their last argument must be a non-null pointer to an integer.
277 They may evaluate their arguments zero or multiple times, so the
278 arguments should not have side effects.
281 They are not necessarily constant expressions, even if all their
282 arguments are constant expressions.
286 @item INT_ADD_OK (@var{a}, @var{b}, @var{r})
288 Compute the sum of @var{a} and @var{b}. If it fits into
289 @code{*@var{r}}, store it there and yield 1. Otherwise yield
290 0, possibly modifying @code{*@var{r}} to an unspecified value.
291 See above for restrictions.
293 @item INT_SUBTRACT_OK (@var{a}, @var{b}, @var{r})
294 @findex INT_SUBTRACT_OK
295 Compute the difference between @var{a} and @var{b}. If it fits into
296 @code{*@var{r}}, store it there and yield 1. Otherwise yield
297 0, possibly modifying @code{*@var{r}} to an unspecified value.
298 See above for restrictions.
300 @item INT_MULTIPLY_OK (@var{a}, @var{b}, @var{r})
301 @findex INT_MULTIPLY_OK
302 Compute the product of @var{a} and @var{b}. If it fits into
303 @code{*@var{r}}, store it there and yield 1. Otherwise yield
304 0, possibly modifying @code{*@var{r}} to an unspecified value.
305 See above for restrictions.
308 Other macros are available if you need wrapped-around results when
309 overflow occurs (@pxref{Wraparound Arithmetic}), or if you need to
310 check for overflow in operations other than addition, subtraction, and
311 multiplication (@pxref{Integer Type Overflow}).
313 @node Wraparound Arithmetic
314 @subsection Wraparound Arithmetic with Integers
316 @cindex wraparound integer arithmetic
318 Signed integer arithmetic has undefined behavior on overflow in C@.
319 Although almost all modern computers use two's complement signed
320 arithmetic that is well-defined to wrap around, C compilers routinely
321 optimize assuming that signed integer overflow cannot occur, which
322 means that a C program cannot easily get at the underlying machine
323 arithmetic. For example, on a typical machine with 32-bit two's
324 complement @code{int} the expression @code{INT_MAX + 1} does not
325 necessarily yield @code{INT_MIN}, because the compiler may do
326 calculations with a 64-bit register, or may generate code that
327 traps on signed integer overflow.
329 The following macros work around this problem by storing the
330 wraparound value, i.e., the low-order bits of the correct answer, and
331 by yielding an overflow indication. For example, if @code{i} is of
332 type @code{int}, @code{INT_ADD_WRAPV (INT_MAX, 1, &i)} sets @code{i}
333 to @code{INT_MIN} and yields 1 on a two's complement machine.
334 @xref{Integer Type Overflow}.
339 #include <intprops.h>
342 /* Print the low order bits of A * B,
343 reporting whether overflow occurred. */
345 print_product (long int a, long int b)
348 int overflow = INT_MULTIPLY_WRAPV (a, b, &r);
349 printf ("result is %ld (%s)\n", r,
356 These macros work for both signed and unsigned integers, so they can
357 be used with integer types like @code{time_t} that may or may not be
358 signed, depending on the platform.
360 These macros have the following restrictions:
364 Their first two arguments must be integer expressions.
367 Their last argument must be a non-null pointer to an integer.
370 They may evaluate their arguments zero or multiple times, so the
371 arguments should not have side effects.
374 They are not necessarily constant expressions, even if all their
375 arguments are constant expressions.
379 @item INT_ADD_WRAPV (@var{a}, @var{b}, @var{r})
380 @findex INT_ADD_WRAPV
381 Store the low-order bits of the sum of @var{a} and @var{b} into
382 @code{*@var{r}}. Yield 1 if overflow occurred, 0 if the
383 low-order bits are the mathematically-correct sum. See above for
386 @item INT_SUBTRACT_WRAPV (@var{a}, @var{b}, @var{r})
387 @findex INT_SUBTRACT_WRAPV
388 Store the low-order bits of the difference between @var{a} and @var{b}
389 into @code{*@var{r}}. Yield 1 if overflow occurred, 0 if the
390 low-order bits are the mathematically-correct difference. See above
393 @item INT_MULTIPLY_WRAPV (@var{a}, @var{b}, @var{r})
394 @findex INT_MULTIPLY_WRAPV
395 Store the low-order bits of the product of @var{a} and @var{b} into
396 @code{*@var{r}}. Yield 1 if overflow occurred, 0 if the
397 low-order bits are the mathematically-correct product. See above for
402 If your code includes @code{<intprops.h>} only for these @code{_WRAPV}
403 macros, you may prefer to use Gnulib's @code{stdckdint-h} module
404 instead, as it supports similar macros that were standardized in C23
405 and are therefore independent of Gnulib if your code can assume C23 or
406 later. @xref{stdckdint.h}.
408 Other macros are available if you do not need wrapped-around results
409 when overflow occurs (@pxref{Checking Integer Overflow}), or if you
410 need to check for overflow in operations other than addition,
411 subtraction, and multiplication (@pxref{Integer Type Overflow}).
413 @node Integer Type Overflow
414 @subsection Integer Type Overflow
416 @cindex integer type overflow
417 @cindex overflow, integer type
419 Although unsigned integer arithmetic wraps around modulo a power of
420 two, signed integer arithmetic has undefined behavior on overflow in
421 C@. Almost all modern computers use two's complement signed
422 arithmetic that is well-defined to wrap around, but C compilers
423 routinely optimize based on the assumption that signed integer
424 overflow cannot occur, which means that a C program cannot easily get
425 at the underlying machine behavior. For example, the signed integer
426 expression @code{(a + b < b) != (a < 0)} is not a reliable test for
427 whether @code{a + b} overflows, because a compiler can assume that
428 signed overflow cannot occur and treat the entire expression as if it
431 These macros yield 1 if the corresponding C operators overflow, 0 otherwise.
432 They work correctly on all known practical hosts, and do not
433 rely on undefined behavior due to signed arithmetic overflow. They
434 are integer constant expressions if their arguments are. They
435 are typically easier to use than the integer range overflow macros
436 (@pxref{Integer Range Overflow}), and they support more operations and
437 evaluation contexts than the integer overflow checking macros
438 (@pxref{Checking Integer Overflow}) or the wraparound macros
439 (@pxref{Wraparound Arithmetic}).
441 These macros can be tricky to use with arguments narrower than
442 @code{int}. For example, in the common case with 16-bit @code{short
443 int} and 32-bit @code{int}, if @code{a} and @code{b} are of type
444 @code{short int} then @code{INT_MULTIPLY_OVERFLOW (a, b)} always
445 yields 0, as @code{a * b} cannot overflow due to C's rule that
446 @code{a} and @code{b} are widened to @code{int} before multiplying.
447 For this reason, often it is better to use the integer overflow
448 checking macros (@pxref{Checking Integer Overflow}) or the wraparound
449 macros (@pxref{Wraparound Arithmetic}) when checking for overflow in
450 addition, subtraction, or multiplication.
455 #include <intprops.h>
459 /* Print A * B if in range, an overflow
460 indicator otherwise. */
462 print_product (long int a, long int b)
464 if (INT_MULTIPLY_OVERFLOW (a, b))
465 printf ("multiply would overflow");
467 printf ("product is %ld", a * b);
470 /* Does the product of two ints always fit
473 INT_PRODUCTS_FIT_IN_LONG
474 = ! (INT_MULTIPLY_OVERFLOW
475 ((long int) INT_MIN, INT_MIN))
480 These macros have the following restrictions:
484 Their arguments must be integer expressions.
487 They may evaluate their arguments zero or multiple times, so the
488 arguments should not have side effects.
492 These macros are tuned for their last argument being a constant.
495 @item INT_ADD_OVERFLOW (@var{a}, @var{b})
496 @findex INT_ADD_OVERFLOW
497 Yield 1 if @code{@var{a} + @var{b}} would overflow, 0 otherwise. See above for
500 @item INT_SUBTRACT_OVERFLOW (@var{a}, @var{b})
501 @findex INT_SUBTRACT_OVERFLOW
502 Yield 1 if @code{@var{a} - @var{b}} would overflow, 0 otherwise. See above for
505 @item INT_NEGATE_OVERFLOW (@var{a})
506 @findex INT_NEGATE_OVERFLOW
507 Yields 1 if @code{-@var{a}} would overflow, 0 otherwise.
508 See above for restrictions.
510 @item INT_MULTIPLY_OVERFLOW (@var{a}, @var{b})
511 @findex INT_MULTIPLY_OVERFLOW
512 Yield 1 if @code{@var{a} * @var{b}} would overflow, 0 otherwise. See above for
515 @item INT_DIVIDE_OVERFLOW (@var{a}, @var{b})
516 @findex INT_DIVIDE_OVERFLOW
517 Yield 1 if @code{@var{a} / @var{b}} would overflow, 0 otherwise. See above for
518 restrictions. Division overflow can happen on two's complement hosts
519 when dividing the most negative integer by @minus{}1. This macro does
520 not check for division by zero.
522 @item INT_REMAINDER_OVERFLOW (@var{a}, @var{b})
523 @findex INT_REMAINDER_OVERFLOW
524 Yield 1 if @code{@var{a} % @var{b}} would overflow, 0 otherwise. See above for
525 restrictions. Remainder overflow can happen on two's complement hosts
526 when dividing the most negative integer by @minus{}1; although the
527 mathematical result is always 0, in practice some implementations
528 trap, so this counts as an overflow. This macro does not check for
531 @item INT_LEFT_SHIFT_OVERFLOW (@var{a}, @var{b})
532 @findex INT_LEFT_SHIFT_OVERFLOW
533 Yield 1 if @code{@var{a} << @var{b}} would overflow, 0 otherwise. See above for
534 restrictions. The C standard says that behavior is undefined for
535 shifts unless 0@leq{}@var{b}<@var{w} where @var{w} is @var{a}'s word
536 width, and that when @var{a} is negative then @code{@var{a} <<
537 @var{b}} has undefined behavior, but this macro does not check these
541 @node Integer Range Overflow
542 @subsection Integer Range Overflow
544 @cindex integer range overflow
545 @cindex overflow, integer range
547 These macros yield 1 if the corresponding C operators might not yield
548 numerically correct answers due to arithmetic overflow, and 0 if if
549 the operators do not overflow. They do not
550 rely on undefined or implementation-defined behavior. They are
551 integer constant expressions if their arguments are. Their
552 implementations are simple and straightforward, but they are typically
553 harder to use than the integer type overflow macros. @xref{Integer
556 Although the implementation of these macros is similar to that
557 suggested in the SEI CERT C Secure Coding Standard,
559 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap,
560 INT30-C@. Ensure that unsigned integer operations do not wrap}'' and
561 ``@url{https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow,
562 INT32-C@. Ensure that operations on signed integers do not result in
563 overflow}'', Gnulib's implementation was derived independently of
569 #include <intprops.h>
574 print_product (long int a, long int b)
576 if (INT_MULTIPLY_RANGE_OVERFLOW (a, b, LONG_MIN, LONG_MAX))
577 printf ("multiply would overflow");
579 printf ("product is %ld", a * b);
582 /* Does the product of two ints always fit
585 INT_PRODUCTS_FIT_IN_LONG
586 = ! (INT_MULTIPLY_RANGE_OVERFLOW
587 ((long int) INT_MIN, (long int) INT_MIN,
593 These macros have the following restrictions:
597 Their arguments must be integer expressions.
600 They may evaluate their arguments zero or multiple times, so
601 the arguments should not have side effects.
604 The arithmetic arguments (including the @var{min} and @var{max}
605 arguments) must be of the same integer type after the usual arithmetic
606 conversions, and the type must have minimum value @var{min} and
607 maximum @var{max}. Unsigned values should use a zero @var{min} of the
608 proper type, for example, @code{(unsigned int) 0}.
612 These macros are tuned for constant @var{min} and @var{max}. For
613 commutative operations such as @code{@var{a} + @var{b}}, they are also
614 tuned for constant @var{b}.
617 @item INT_ADD_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
618 @findex INT_ADD_RANGE_OVERFLOW
619 Yield 1 if @code{@var{a} + @var{b}} would overflow in
620 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
621 See above for restrictions.
623 @item INT_SUBTRACT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
624 @findex INT_SUBTRACT_RANGE_OVERFLOW
625 Yield 1 if @code{@var{a} - @var{b}} would overflow in
626 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
627 See above for restrictions.
629 @item INT_NEGATE_RANGE_OVERFLOW (@var{a}, @var{min}, @var{max})
630 @findex INT_NEGATE_RANGE_OVERFLOW
631 Yield 1 if @code{-@var{a}} would overflow in [@var{min},@var{max}]
632 integer arithmetic, 0 otherwise. See above for restrictions.
634 @item INT_MULTIPLY_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
635 @findex INT_MULTIPLY_RANGE_OVERFLOW
636 Yield 1 if @code{@var{a} * @var{b}} would overflow in
637 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
638 See above for restrictions.
640 @item INT_DIVIDE_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
641 @findex INT_DIVIDE_RANGE_OVERFLOW
642 Yield 1 if @code{@var{a} / @var{b}} would overflow in
643 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
644 See above for restrictions.
645 Division overflow can happen on two's complement hosts when dividing
646 the most negative integer by @minus{}1. This macro does not check for
649 @item INT_REMAINDER_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
650 @findex INT_REMAINDER_RANGE_OVERFLOW
651 Yield 1 if @code{@var{a} % @var{b}} would overflow in
652 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
653 See above for restrictions.
654 Remainder overflow can happen on two's complement hosts when dividing
655 the most negative integer by @minus{}1; although the mathematical
656 result is always 0, in practice some implementations trap, so this
657 counts as an overflow. This macro does not check for division by
660 @item INT_LEFT_SHIFT_RANGE_OVERFLOW (@var{a}, @var{b}, @var{min}, @var{max})
661 @findex INT_LEFT_SHIFT_RANGE_OVERFLOW
662 Yield 1 if @code{@var{a} << @var{b}} would overflow in
663 [@var{min},@var{max}] integer arithmetic, 0 otherwise.
664 See above for restrictions.
665 Here, @var{min} and @var{max} are for @var{a} only, and @var{b} need
666 not be of the same type as the other arguments. The C standard says
667 that behavior is undefined for shifts unless 0@leq{}@var{b}<@var{w}
668 where @var{w} is @var{a}'s word width, and that when @var{a} is negative
669 then @code{@var{a} << @var{b}} has undefined behavior, but this macro
670 does not check these other restrictions.