0

The following code runs infinitely. Here, prices is a vector of int type with 0 elements.

for (int i = 0; i < (prices.size()-1); i++)
{
}

Can anyone please explain to me the reason why the loop condition is failing? I am running the code in Visual Studio 2019 community edition.

Faysal
  • 35
  • 6
  • It's likely a bug that MSVC's warning misses this case, but it's always a good idea to try at least a couple [different compilers](https://gcc.godbolt.org/z/6Ynm_9) to catch things one might miss. – chris May 25 '20 at 18:32
  • 1
    Write your code like this `for (int i = 0; i + 1 < prices.size(); i++)` Now it will work. – john May 25 '20 at 18:46
  • @chris MSVC is good at warning about signed/unsigned comparisons. If anyone is missing anything it's the OP. – john May 25 '20 at 18:48
  • 1
    `prices.size()` data type is unsigned int. You subtract 1 from zero and get `i < 2^32 - 1` in the for comparison clause. MSVC should had a warning though – dgrandm May 25 '20 at 18:48
  • @john, [It doesn't here](https://gcc.godbolt.org/z/aAJvfS). That warning is level 3, so `/W4` should enable it. The fact that it normally warns about these is why I said it's likely a bug. – chris May 25 '20 at 18:49
  • @chris Interesting, I don't have any explanation – john May 25 '20 at 18:59

0 Answers0