Search code examples
c++floating-point-exceptions

Floating point exception?


Very straight forward. The code below is from one of my functions:

int i, j;
for (i = 0; i < m; i++) {
    for (j = 0; j < numberOfVariables; j++) {
        if ((j % i) == 0 && i != 0) {
            table[i][j] = 1;
        }
    }
}

When I call it, I get a floating point exception. Except that I am working with no floating points. So what's happening exactly?


Solution

  • When i is zero, j % i involves division by zero, which is not allowed.

    To prevent it, you need to change this:

          if ((j % i) == 0 && i != 0) {
    

    to this:

          if (i != 0 && (j % i) == 0) {
    

    (taking advantage of the short-circuiting behavior of &&: if the left-hand operand evaluates to false, then the right-hand operand will never be evaluated).