Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New to C++, created something that outputs seemingly infinite numbers. Could someone explain why?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading