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?
>Solution :
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.