pre-boost Home Libraries People FAQ More

PrevUpHomeNext

Problem

Arithmetic operations in C++ are NOT guaranteed to yield a correct mathematical result. This feature is inherited from the early days of C. The behavior of int, unsigned int and others were designed to map closely to the underlying hardware. Computer hardware implements these types as a fixed number of bits. When the result of arithmetic operations exceeds this number of bits, the result will not be arithmetically correct. The following example illustrates this problem.

int f(int x, int y){
    // this returns an invalid result for some legal values of x and y !
    return x + y;
}

It is incumbent up the C/C++ programmer to guarantee that this behavior does not result in incorrect or unexpected operation of the program. There are no language facilities which do this. They have to be explicitly addressed in the program code. There are a number of ways to do this. See[INT32-C] seems to recommend the following approach.

int f(int x, int y){
  if (((y > 0) && (x > (INT_MAX - y))) 
  || ((y < 0) && (x < (INT_MIN - x)))) {
    /* Handle error */
  }
  return x + y;
}

This will indeed trap the error. However, it would be tedious and laborious for a programmer to do alter his code to do. Altering code in this way for all arithmetic operations would likely render the code unreadable and add another source of potential programming errors. This approach is clearly not functional when the expression is even a little more complex as is shown in the following example.

int f(int x, int y, int z){
    // this returns an invalid result for some legal values of x and y !
    return x + y * z;
}

PrevUpHomeNext