Enforce Correct Integer Arithmetic using the C++ Safe Numerics Library

The Boost Safe Numerics library, created by Robert Ramey aims to enforce correct mathematical operations with the C++ language.

Why are safer numeric operations needed?

C++ inherited the behavior of the integral types (int, unsigned, long, etc.) from the C language, where they were designed to map closely to the underlying processor hardware. The types were originally mapped to a specific number of bits. When the result of an arithmetical operation exceeded the fixed capacity, an overflow occurs and the result is incorrect. Adding to the difficulty is the fact that C/C++ will automatically convert among integral types, for example when implementing binary operations.

I know that in my own programs, I have been bitten by arithmetical overflow numerous times.

The Safe Numerics library provides drop-in replacements for built-in integral types to ensure that mathematical operations on integral types are verified for correctness with as little runtime overhead as possible. Operations are guaranteed to be either arithmetically correct, to emit a compilation error, or to trigger a runtime exception.

#include <boost/safe_numeric/safe_integer.hpp>
using namespace boost::numeric;
safe<int> f(safe<int> x, safe<int> y){
  return x + y; // throw exception if correct
                // result cannot be returned
}

Now, if you’re an embedded developer you may have stopped reading at “exception”. No need to fear – exceptions are not actually required for this library. You can select or define an exception policy class to:

  • Trap any case which might generate an exception at compile-time (using the trap_exception policy)
  • Specify a custom function to invoke at runtime (pick your favorite variant of panic(), assert(), abort(), exit())

The library has a handful of other features, such as the ability to define promotion policies and enforce ranges on an integer, and to define a safe numeric literal.

The Safe Numerics library is well-documented. Documentation includes tutorials, case studies, and advice for eliminating runtime penalties.

The library requires C++14, as features specific to that version allow for minimization of runtime overhead.

You must install the following Boost Libraries to use this library:

  • MPL
  • Integer
  • Config
  • Concept Checking
  • Tribool
  • Enable_if

You can find this library on GitHub or clone it directly:

git clone git@github.com:boostorg/safe_numerics.git

Further Reading

For more information about the Safe Numerics library, check out the following:

One Reply to “Enforce Correct Integer Arithmetic using the C++ Safe Numerics Library”

Share Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.