2

I found this code on a q&a platform.

#include <iostream>
int main()
{
for (int i = 0; i < 300; i++)
std::cout << i << " " << i * 12345678 << std::endl;
}

At first sight, this seems normal but instead it runs infinitely. Results at : https://ideone.com/7F88MV

Now I changed the std::endl to "\n" and it behaved normal this time running for 300 times, terminating at i=299.

So what is going on with the std::endl keyword ?

jovian
  • 121
  • 1
  • 3
  • 3
    The program causes undefined behaviour due to signed integer overflow, which means anything can happen – M.M Apr 11 '20 at 07:22
  • 1
    Okay.. I got your point. I changed int to long long int and got normal results. But if it happend due to signed integer overflow then, why doesn't it happen in cases where I use int but do not put std::endl at the end ? In those cases the loop terminates as normal. – jovian Apr 11 '20 at 07:38
  • 3
    hard to say really, the language is only defined for valid programs and this isn't one – M.M Apr 11 '20 at 08:41

0 Answers0