-1

I am new to C++, and wanted to test my knowledge in while loops, I use MS Visual Studios 2019, and created this code

int main() {
    int i = 12;
    while (i > 10) {
        cout << i;
        i++;
    }
    return 0;
}

When I run this, I am met with a seemingly infinite line of numbers that continues to run. I tried using this on w3schools IDE and it prints out a long string. I am aware ints are up to 2,147,483,647 yet it doesnt end there, or even have it in there. Could someone explain to me what happened?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
noctite
  • 9
  • 3
  • Firstly, an `int` on *your platform* may be up to `2147483647`. That is not guaranteed (the upper limit of an `int` is implementation-defined, and the standard only requires that an `int` can represent values to `65535`). Regardless of what the limit is, consider what happens when an `int` with the maximum value it can represent is *incremented*. The behaviour of a program doing that operation is *undefined* - there is no guarantee of wrap-around, nor is there a guarantee that your loop will end, no guarantee of anything. – Peter Mar 08 '23 at 04:59
  • @Peter the standard only requires an int can represent values up to 32767 – M.M Mar 08 '23 at 05:01
  • @M.M Thanks for that. For some reason I typed in the maximum required value of an `unsigned`. – Peter Mar 08 '23 at 05:02
  • Side note: There is no defined maximum value for any of the basic integer types. `int` is defined as being at least 16 bit and no larger then `long`. `long` can be no larger than `long long`. And `'long long` currently has no mandated upper limit. – user4581301 Mar 08 '23 at 05:43
  • @user4581301 True, but it's also a statement that is easily misinterpreted. I've seen beginners start with a similar statement, and infer that `long long` is an unbounded type. When it is *actually* a type required by the standard to be able to represent the range `-9223372036854775807` to `9223372036854775807`, and it is allowed (not required and certainly not guaranteed) for an implementation to support a `long long` with a larger range of values. – Peter Mar 08 '23 at 08:01

1 Answers1

5

It may look like a seemingly infinite number of numbers will be printed, but the program has undefined behavior due to signed integer overflow:

int main() {
    int i = 12;
    while (i > 10) {
        cout << i;
        i++;         // will eventually be INT_MAX + 1 and UB
     }
     return 0;
}

Since the program will eventually overflow i, the behavior of the whole program is undefined.

On many platforms, the loop will go on and eventually i will go from INT_MAX to INT_MIN and then will the loop end (because INT_MIN is not > 10) - but, it's undefined. Don't allow your program to cause signed integer overflows.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108