-3

For reasons I can't understand, this crashes with a floating point exception.

This is surprising, because I do not appear to have any floating point operations in my code and I don't set i to 0. I've even added i * i != 0 to my code to make sure that this is the case.

Please could someone help me?

This is my code:

#include <iostream>

int main() {
    const int A = 42;
    int i;
    i * i != 0;
    for (i = 1; i < 99999999; i++) {
        if (A % (i * i) == 0) {
            std::cout << i << std::endl;
        }
    }   
}
OMGtechy
  • 7,935
  • 8
  • 48
  • 83

1 Answers1

3

Your code is invoking undefined behavior, because

i * i != 0

appears before initializing i, thus you can understand your program's behavior because there is undefined behavior happening, and one of the things that could happen is that i == 0 at some point.

Also, the statement does absolutely nothing so it's pointless.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • @JesperJuhl Yes, that's why one of the possible things is that `i == 0` at some point. – Iharob Al Asimi Mar 12 '17 at 22:15
  • `i * i != 0` - This is defined - it does nothing except doing the calculation and comparison - then throwing away the result – Ed Heal Mar 12 '17 at 22:19
  • Obviously. I'm just trying to say that that is not what your answer says. Terminoligy​ and proper language is important and your answer is not clear. That's all. – Jesper Juhl Mar 12 '17 at 22:19
  • @JesperJuhl Thank you for pointing it our, I appreciate your opinion. Is it clearer now? – Iharob Al Asimi Mar 12 '17 at 22:20
  • @Iharob Al Asimi The part I mostly object to is "behavior is explicable" - what does that mean? That's not proper english as far as I know. Do you perhaps mean "behaviour is undefined"? ?? – Jesper Juhl Mar 12 '17 at 22:22
  • this is not the problem, although the points are valid, see my other comments on the question :) – OMGtechy Mar 12 '17 at 22:31
  • i tried adding that so "i" doesn't somehow become 0. because somehow i was getting 0 in "i" from loop – Luka Rusadze LukaRuso Mar 12 '17 at 22:43