SaleenS7 - 1 year ago 102
C++ Question

# How is this an infinite loop?

I wrote this program for an intro to comp sci class. All it is is a demonstration of using a while loop. My professor marked this program as having an infinite loop, but I don't understand how it is an infinite loop because it terminates when -1 is entered.

``````int main() {

int accountNum, balance, totalOfItems, totalOfCredits, creditLimit; //Integers for the user to input

while (accountNum != -1)
{
cout << "Enter account number" << endl;
cin >> accountNum;
cout << "Enter balance" << endl;
cin >> balance;
cout << "Enter total of all items charged this month" << endl;
cin >> totalOfItems;
cout << "Enter total of all credits applied to the account this month" << endl;
cin >> totalOfCredits;
cout << "Enter credit limit" << endl;
cin >> creditLimit;

int newBalance = balance + totalOfItems - totalOfCredits;

if (newBalance > creditLimit)
{
cout << "Account Number: " << accountNum << "\nCredit Limit: " << creditLimit << "\nNew Balance " << newBalance << endl;
cout << "Credit limit exceeded." << endl;
} else {
cout << "New balance : " << newBalance << endl;
}
}
return 0;
}
``````

1. `accountNum` is not initialized, before it is used. This results in undefined behavior.
2. Even if `-1` is entered, the loop will still slog through, and all the remaining input must still be entered.
3. If invalid input is entered, `std::cin` enters error state, and will loop forever.