Integer Properties
==================

The intprops module consists of an include file <intprops.h> that defines several macros useful for testing properties of integer types.

Integer overflow is a common source of problems in programs written in C and other languages.  In some cases, such as signed integer arithmetic in C programs, the resulting behavior is undefined, and practical platforms do not always behave as if integers wrap around reliably.  In other cases, such as unsigned integer arithmetic in C, the resulting behavior is well-defined, but programs may still misbehave badly after overflow occurs.

Many techniques have been proposed to attack these problems.  These include precondition testing, wraparound behavior where signed integer arithmetic is guaranteed to be modular, saturation semantics where overflow reliably yields an extreme value, undefined behavior sanitizers where overflow is guaranteed to trap, and various static analysis techniques.

Gnulib supports wraparound arithmetic and precondition testing, as these are relatively easy to support portably and efficiently.  There are two families of precondition tests: the first, for integer types, is easier to use, while the second, for integer ranges, has a simple and straightforward portable implementation.

Like other Gnulib modules, the implementation of the intprops module assumes that integers use a two's complement representation, but it does not assume that signed integer arithmetic wraps around. See Other portability assumptions.

Arithmetic Type Properties
--------------------------

TYPE_IS_INTEGER (T) is an arithmetic constant expression that is 1 if the arithmetic type T is an integer type. _Bool counts as an integer type.

TYPE_SIGNED (T) is an arithmetic constant expression that is 1 if the real type T is a signed integer type or a floating type.  If T is an integer type, TYPE_SIGNED (T) is an integer constant expression.

EXPR_SIGNED (E) is 1 if the real expression E has a signed integer type or a floating type.  If E is an integer constant expression or an arithmetic constant expression, EXPR_SIGNED (E) is likewise.  The expression E is not evaluated, and EXPR_SIGNED (E) is typically optimized to a constant.

Example usage:

     #include <intprops.h>
     #include <sys/types.h>

     enum
     {
       clock_t_is_integer = TYPE_IS_INTEGER (clock_t),
       uid_t_is_signed = TYPE_SIGNED (uid_t)
     };

     int
     CLOCKS_PER_SEC_is_signed (void)
     {
       return EXPR_SIGNED (CLOCKS_PER_SEC);
     }

Integer Bounds
--------------

INT_BUFSIZE_BOUND (T) is an integer constant expression that is a bound on the size of the string representing an integer type or expression T in decimal notation, including the terminating null character and any leading - character.  For example, if INT_BUFSIZE_BOUND (int) is 12, any value of type int can be represented in 12 bytes or less, including the terminating null.  The bound is not necessarily tight.

Example usage:

     #include <intprops.h>
     #include <stdio.h>
     int
     int_strlen (int i)
     {
       char buf[INT_BUFSIZE_BOUND (int)];
       return sprintf (buf, "%d", i);
     }

INT_STRLEN_BOUND (T) is an integer constant expression that is a bound on the length of the string representing an integer type or expression T in decimal notation, including any leading - character.  This is one less than INT_BUFSIZE_BOUND (T).

TYPE_MINIMUM (T) and TYPE_MAXIMUM (T) are integer constant expressions equal to the minimum and maximum values of the integer type T.  These expressions are of the type T.

Example usage:

     #include <stdbool.h>
     #include <sys/types.h>
     #include <intprops.h>
     bool
     in_off_t_range (long long int a)
     {
       return TYPE_MINIMUM (off_t) <= a && a <= TYPE_MAXIMUM (off_t);
     }

Checking Integer Overflow
-------------------------

Signed integer arithmetic has undefined behavior on overflow in C. Although almost all modern computers use two's complement signed arithmetic that is well-defined to wrap around, C compilers routinely optimize assuming that signed integer overflow cannot occur, which means that a C program cannot easily get at the underlying machine arithmetic.  For example:

     if ((a + b < b) == (a < 0))
       a += b;
     else
       printf ("overflow\n");

might not work as expected if a and b are signed, because a compiler can assume that signed overflow cannot occur and treat the entire if expression as if it were true.  And even if a is unsigned, the expression might not work as expected if b is negative or is wider than a.

The following macros work around this problem by returning an overflow indication while computing the sum, difference, or product of two integers.  For example, if i is of type int, INT_ADD_OK (INT_MAX - 1, 1, &i) sets i to INT_MAX and returns true, whereas INT_ADD_OK (INT_MAX, 1, &i) returns false.

Example usage:

     #include <intprops.h>
     #include <stdio.h>

     /* Compute A * B, reporting whether overflow occurred.  */
     void
     print_product (long int a, long int b)
     {
       long int r;
       if (INT_MULTIPLY_OK (a, b, &r))
         printf ("result is %ld\n", r);
       else
         printf ("overflow\n");
     }

These macros work for both signed and unsigned integers, so they can be used with integer types like time_t that may or may not be signed, depending on the platform.

These macros have the following restrictions:

  * Their first two arguments must be integer expressions.

  * Their last argument must be a non-null pointer to an integer.

  * They may evaluate their arguments zero or multiple times, so the arguments should not have side effects.

  * They are not necessarily constant expressions, even if all their arguments are constant expressions.

INT_ADD_OK (A, B, R)
     Compute the sum of A and B.  If it fits into *R, store it there and return true.  Otherwise return false, possibly modifying *R to an unspecified value. See above for restrictions.

INT_SUBTRACT_OK (A, B, R)
     Compute the difference between A and B.  If it fits into *R, store it there and return true.  Otherwise return false, possibly modifying *R to an unspecified value. See above for restrictions.

INT_MULTIPLY_OK (A, B, R)
     Compute the product of A and B.  If it fits into *R, store it there and return true.  Otherwise return false, possibly modifying *R to an unspecified value. See above for restrictions.

Other macros are available if you need wrapped-around results when overflow occurs (see Wraparound Arithmetic), or if you need to check for overflow in operations other than addition, subtraction, and multiplication (see Integer Type Overflow).

Wraparound Arithmetic with Integers
-----------------------------------

Signed integer arithmetic has undefined behavior on overflow in C. Although almost all modern computers use two's complement signed arithmetic that is well-defined to wrap around, C compilers routinely optimize assuming that signed integer overflow cannot occur, which means that a C program cannot easily get at the underlying machine arithmetic.  For example, on a typical machine with 32-bit two's complement int the expression INT_MAX + 1 does not necessarily yield INT_MIN, because the compiler may do calculations with a 64-bit register, or may generate code that traps on signed integer overflow.

The following macros work around this problem by storing the wraparound value, i.e., the low-order bits of the correct answer, and by returning an overflow indication.  For example, if i is of type int, INT_ADD_WRAPV (INT_MAX, 1, &i) sets i to INT_MIN and returns 1 on a two's complement machine. See Integer Type Overflow.

Example usage:

     #include <intprops.h>
     #include <stdio.h>

     /* Print the low order bits of A * B,
        reporting whether overflow occurred.  */
     void
     print_product (long int a, long int b)
     {
       long int r;
       int overflow = INT_MULTIPLY_WRAPV (a, b, &r);
       printf ("result is %ld (%s)\n", r,
               (overflow
                ? "after overflow"
                : "no overflow"));
     }

These macros work for both signed and unsigned integers, so they can be used with integer types like time_t that may or may not be signed, depending on the platform.

These macros have the following restrictions:

  * Their first two arguments must be integer expressions.

  * Their last argument must be a non-null pointer to an integer.

  * They may evaluate their arguments zero or multiple times, so the arguments should not have side effects.

  * They are not necessarily constant expressions, even if all their arguments are constant expressions.

INT_ADD_WRAPV (A, B, R)
     Store the low-order bits of the sum of A and B into *R.  Return true if overflow occurred, false if the low-order bits are the mathematically-correct sum.  See above for restrictions.

INT_SUBTRACT_WRAPV (A, B, R)
     Store the low-order bits of the difference between A and B into *R.  Return true if overflow occurred, false if the low-order bits are the mathematically-correct difference.  See above for restrictions.

INT_MULTIPLY_WRAPV (A, B, R)
     Store the low-order bits of the product of A and B into *R.  Return true if overflow occurred, false if the low-order bits are the mathematically-correct product.  See above for restrictions.

Other macros are available if you do not need wrapped-around results when overflow occurs (see Checking Integer Overflow), or if you need to check for overflow in operations other than addition, subtraction, and multiplication (see Integer Type Overflow).

Integer Type Overflow
---------------------

Although unsigned integer arithmetic wraps around modulo a power of two, signed integer arithmetic has undefined behavior on overflow in C.  Almost all modern computers use two's complement signed arithmetic that is well-defined to wrap around, but C compilers routinely optimize based on the assumption that signed integer overflow cannot occur, which means that a C program cannot easily get at the underlying machine behavior.  For example, the signed integer expression (a + b < b) != (a < 0) is not a reliable test for whether a + b overflows, because a compiler can assume that signed overflow cannot occur and treat the entire expression as if it were false.

These macros yield 1 if the corresponding C operators might not yield numerically correct answers due to arithmetic overflow of an integer type.  They work correctly on all known practical hosts, and do not rely on undefined behavior due to signed arithmetic overflow.  They are integer constant expressions if their arguments are.  They are typically easier to use than the integer range overflow macros (see Integer Range Overflow), and they support more operations and evaluation contexts than the wraparound macros (see Wraparound Arithmetic).

Example usage:

     #include <intprops.h>
     #include <limits.h>
     #include <stdio.h>

     /* Print A * B if in range, an overflow
        indicator otherwise.  */
     void
     print_product (long int a, long int b)
     {
       if (INT_MULTIPLY_OVERFLOW (a, b))
         printf ("multiply would overflow");
       else
         printf ("product is %ld", a * b);
     }

     /* Does the product of two ints always fit
        in a long int?  */
     enum {
       INT_PRODUCTS_FIT_IN_LONG
         = ! (INT_MULTIPLY_OVERFLOW
              ((long int) INT_MIN, INT_MIN))
     };

These macros have the following restrictions:

  * Their arguments must be integer expressions.

  * They may evaluate their arguments zero or multiple times, so the arguments should not have side effects.

These macros are tuned for their last argument being a constant.

INT_ADD_OVERFLOW (A, B)
     Yield 1 if A + B would overflow.  See above for restrictions.

INT_SUBTRACT_OVERFLOW (A, B)
     Yield 1 if A - B would overflow.  See above for restrictions.

INT_NEGATE_OVERFLOW (A)
     Yields 1 if -A would overflow.  See above for restrictions.

INT_MULTIPLY_OVERFLOW (A, B)
     Yield 1 if A * B would overflow.  See above for restrictions.

INT_DIVIDE_OVERFLOW (A, B)
     Yields 1 if A / B would overflow.  See above for restrictions.  Division overflow can happen on two's complement hosts when dividing the most negative integer by -1.  This macro does not check for division by zero.

INT_REMAINDER_OVERFLOW (A, B)
     Yield 1 if A % B would overflow.  See above for restrictions.  Remainder overflow can happen on two's complement hosts when dividing the most negative integer by -1; although the mathematical result is always 0, in practice some implementations trap, so this counts as an overflow.  This macro does not check for division by zero.

INT_LEFT_SHIFT_OVERFLOW (A, B)
     Yield 1 if A << B would overflow.  See above for restrictions.  The C standard says that behavior is undefined for shifts unless 0≤B<W where W is A's word width, and that when A is negative then A << B has undefined behavior, but this macro does not check these other restrictions.

Integer Range Overflow
----------------------

These macros yield 1 if the corresponding C operators might not yield numerically correct answers due to arithmetic overflow.  They do not rely on undefined or implementation-defined behavior.  They are integer constant expressions if their arguments are.  Their implementations are simple and straightforward, but they are typically harder to use than the integer type overflow macros.  See Integer Type Overflow.

Although the implementation of these macros is similar to that suggested in the SEI CERT C Secure Coding Standard, in its two sections ``INT30-C. Ensure that unsigned integer operations do not wrap (https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap)'' and ``INT32-C. Ensure that operations on signed integers do not result in overflow (https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow)'', Gnulib's implementation was derived independently of CERT's suggestions.

Example usage:

     #include <intprops.h>
     #include <limits.h>
     #include <stdio.h>

     void
     print_product (long int a, long int b)
     {
       if (INT_MULTIPLY_RANGE_OVERFLOW (a, b, LONG_MIN, LONG_MAX))
         printf ("multiply would overflow");
       else
         printf ("product is %ld", a * b);
     }

     /* Does the product of two ints always fit
        in a long int?  */
     enum {
       INT_PRODUCTS_FIT_IN_LONG
         = ! (INT_MULTIPLY_RANGE_OVERFLOW
              ((long int) INT_MIN, (long int) INT_MIN,
               LONG_MIN, LONG_MAX))
     };

These macros have the following restrictions:

  * Their arguments must be integer expressions.

  * They may evaluate their arguments zero or multiple times, so the arguments should not have side effects.

  * The arithmetic arguments (including the MIN and MAX arguments) must be of the same integer type after the usual arithmetic conversions, and the type must have minimum value MIN and maximum MAX.  Unsigned values should use a zero MIN of the proper type, for example, (unsigned int) 0.

These macros are tuned for constant MIN and MAX.  For commutative operations such as A + B, they are also tuned for constant B.

INT_ADD_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A + B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions.

INT_SUBTRACT_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A - B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions.

INT_NEGATE_RANGE_OVERFLOW (A, MIN, MAX)
     Yield 1 if -A would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions.

INT_MULTIPLY_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A * B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions.

INT_DIVIDE_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A / B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions. Division overflow can happen on two's complement hosts when dividing the most negative integer by -1.  This macro does not check for division by zero.

INT_REMAINDER_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A % B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions. Remainder overflow can happen on two's complement hosts when dividing the most negative integer by -1; although the mathematical result is always 0, in practice some implementations trap, so this counts as an overflow.  This macro does not check for division by zero.

INT_LEFT_SHIFT_RANGE_OVERFLOW (A, B, MIN, MAX)
     Yield 1 if A << B would overflow in [MIN,MAX] integer arithmetic.  See above for restrictions. Here, MIN and MAX are for A only, and B need not be of the same type as the other arguments.  The C standard says that behavior is undefined for shifts unless 0≤B<W where W is A's word width, and that when A is negative then A << B has undefined behavior, but this macro does not check these other restrictions.