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

Endless loop in c++

I am currently learning c++ and I have come to a strange behavior at my code:

#include<iostream>
using namespace std;

int main(){
    int input;
    int counter = 0;
    while (input != 0 && counter <= 100){
        cout << "-----------\n";
        cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
        cin >> input;
        cout << "The number: " << input << "\n";
        counter++;
    }
    return 0;
}

This Program itself works fine, but when I am typing a number as input, which is at least the maximum of the integer datatype + 1, then this loop will be endless (I programmed a stop after 100 loops) and I cannot really explain this to me. In other languages the program just crashes or gives out an error, because the allocated storage is just not high enough for the data typed in, what is logic and I understand that, but why do the loop gets endless here, that does not make any sense, because I cannot do any inputs after this happens, it just keeps doing the loop with the value (integer maxnumber, in my book stands, that the maxnumber can vary from system to system, so I do not type my number) endlessely and I cannot do anything, but watch my console getting flooded with the same 4 lines.

I would really appreciate, if somebody could explain this phenomena to me, I mean it is not crucial, but it catched my interest anyways.

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 :

  1. Your input variable needs to be initialized because you check its value in the while (input != 0 && counter <= 100){ before assigning the input value.
  2. Undefined Behaviour is typical in C++ when exceeding data type limits. These are some common UB.
  3. This post contains the "solution" to your problem
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