0

The value for i keeps decreasing forever. Technically it should stop after first iteration because ans.size()-k = 0, but it doesn't stop. If I put 0 manually over there then it works completely fine.

#include <bits/stdc++.h>
using namespace std;

int main()
{
     vector<int> ans(1);
     int k = 1;
     for (int i = ans.size() - 1; i >= ans.size() - k; --i)
     {
          cout << i << endl;
     }
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
Utsav Patel
  • 25
  • 1
  • 8
  • 1
    Relevant: [Signed/unsigned comparisons](https://stackoverflow.com/q/5416414/580083) – Daniel Langr Jun 15 '22 at 08:53
  • 1
    Please [enable warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) on your compiler. It will tell you what is wrong. – user17732522 Jun 15 '22 at 08:55
  • 2
    -> `i + k >= ans.size()`. – Jarod42 Jun 15 '22 at 08:56
  • @Jarod42 Yes so it should stop when i goes to -1 becasue -1 + 1 = 0 which is not greater than 1 (size of ans vector) – Utsav Patel Jun 15 '22 at 09:02
  • 2
    @UtsavPatel `ans.size()` is **unsigned**, there is no `-1` unsigned value. That it why your version does not work (and Jarod42's version does work). C++ math is not the same as normal math, and the problems when you mix signed and unsigned values are one example of that. – john Jun 15 '22 at 09:35

0 Answers0