0

I got this from a facebook post. What's happening here? See the output in ideone. Output is more than 10 lines.

Code:

#include<iostream> 
using namespace std;

int main()
{
    for (int i = 0; i < 10; ++i)
        cout << i*1000000000 << endl;
}

Ideone Link

Inam
  • 23
  • 4
  • You even tagged it with `overflow`. `9*1000000000 ` doesn't fit into an `int` anymore, which causes overflow, and that's undefined behavior. – Blaze Mar 22 '19 at 10:55
  • 2
    Why can't you copy-paste the output into your question? And why do you think it's wrong or UB? Please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Mar 22 '19 at 10:56
  • Probably compiler logic: "Since `3 * 1000000000 ` overflows, we can assume that `i < 3`. Thus `i < 10` is always true." – molbdnilo Mar 22 '19 at 11:09
  • For a 16-bit int, `3 * 1000000000` will overflow when `i == 1`. So the compiler can assume `i` is always zero, and the condition `i < 10` is always true. For a 32 bit `int`, the compiler can assume `i < 3`. For a 64-bit `int`, the loop will only run ten times. – Peter Mar 22 '19 at 11:42

1 Answers1

3

Your platform most likely has a 32 bit int. So 1'000'000'000 is an int, and the compiler will attempt to evaluate i * 1'000'000'000 as an int too. This results in an overflow from i being 3 onwards.

The behaviour on overflowing a signed integral type is undefined.

Note that this makes the entire program behaviour undefined, which accounts for the multiple lines of output (beyond 10) that you observe.

(If you had chosen 10'000'000'000 say instead then the multiplication would have been evaluated with long long types and the behaviour would be well-defined!)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I know what UB is, but somehow it is always explainable what actually happens. Could you come up with a reason why this specific platform (ideone) causes it to run further than 10 ? – Bart Friederichs Mar 22 '19 at 11:03
  • So due to the undefined behaviour somehow i < 10 condition is true when i >= 10? – Inam Mar 22 '19 at 11:05
  • @Inam: My wildest guess is that the compiler is assuming that `i * 1000000000` *can* fit into an `int`, so therefore `i` must be small, and therefore less than 10. – Bathsheba Mar 22 '19 at 11:13
  • @Inam the point is that due to undefined behaviour; the whole program breaks down. The language that describes what the program should do is invalid. You've written a loop there, but the compiler may or may not decide to make it a loop anyway; but the compiler might detect that it only needs to do 3 loops before the value would overflow... and then bin the other 7 – UKMonkey Mar 22 '19 at 11:16