-3

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?

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
AugustoQ
  • 213
  • 3
  • 14

3 Answers3

8

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

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

Consider the first iteration :

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

&& and || will always evaluate the left operand first, and the condition will short circuit if the condition turns false.

This means that when i != 0, it will evaluate j % i first, and so divide by zero. Note that division by zero is undefined behavior.

You need to replace that line by :

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

This way, when i == 0, (j % i) == 0 will not be evaluated

But instead of doing this check, can't you just directly avoid this case? You can simply iterate i from 1 to m instead so you can also remove the check:

for (i = 1; i < m; i++) {

Edit: Your runtime claiming you encountered a floating point exception is probably wrong and mistook an arithmetic exception as a divide by zero; or it could be due to a compiler optimization. Something along those lines.

asu
  • 1,875
  • 17
  • 27
0

When you evaluate (j % i) == 0 for i=0 in your loop, this is dividing by 0 in the background. Hence the floating point exception.

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

At runtime, it will evaluate that i==0 and skip the modulo evaluation. The way you were doing before was evaluating the modulo before verifying that i!=0.

Jean-Emmanuel
  • 688
  • 8
  • 18