Search code examples
c++operatorsmodulo

Unexpected behavior for % 5 with a dividend of zero


I have following code

#include <iostream>
#include<exception>
#include <cstdlib>
int main(){
  for (int i = 0; i < 100; i++) {
    std::cout << i << " ";
      if (i % 5 == 0) {
        abort();
      }
   }
}

but it only writes 0 and says that abort was called why? i think it should ouput 0 1 2 3 4 and than exit program yes?


Solution

  • Think of % as "remainder after division." 0 / 5 equals 0 with a remainder of 0.