>
>
>
V663. Infinite loop is possible. The 'c…


V663. Infinite loop is possible. The 'cin.eof()' condition is insufficient to break from the loop. Consider adding the 'cin.fail()' function call to the conditional expression.

The analyzer has detected a potential error that may lead to an infinite loop. When you deal with the 'std::istream' class, calling the 'eof()' function is not enough to terminate the loop. If data reading fails, a call of the 'eof()' function will always return 'false'. You need an additional check of the value returned by the 'fail()' function to terminate the loop in this case.

Have a look at an example of incorrect code:

while (!cin.eof())
{
  int x;
  cin >> x;
}

You can fix the error by making the condition a bit more complex:

while (!cin.eof() && !cin.fail())
{ 
  int x;
  cin >> x;
}

However, this option has drawbacks. Correct and the simplest code version looks as follows:

int x;
while(cin >> x) {
  ....;
}

Check out a more detailed discussion on reading from the stream here: Why is iostream::eof inside a loop condition (i.e. 'while (!stream.eof())') considered wrong?

This diagnostic is classified as:

You can look at examples of errors detected by the V663 diagnostic.