AugustoQ AugustoQ - 26 days ago 7
C++ Question

Floating point exception?

Very straight forward:
I have this function in my code that has this as it's body:

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?

Answer

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).