0

Even though s1.size() - s2.size() is under 0, the for loop does not finish...
I hope someone gives me the idea how this occurs.

input:

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

signed main()
{
  string s1, s2;
  getline(cin, s1), getline(cin, s2);
  cout << s1.size() << endl; // 2
  cout << s2.size() << endl; // 3
  for (int i = 0; i <= s1.size() - s2.size(); i++)
  {
    cout << "infinite loop" << endl;
  }


  return 0;
}
ktakehi
  • 249
  • 1
  • 3
  • 13
  • 8
    The `size()` function returns an ***unsigned*** type. Usually also 64 bits wide on 64-bit systems. Mixing signed and unsigned, or integers of different sizes (`int` is commonly 32 bits) arithmetic and comparison usually leads to problems. – Some programmer dude Oct 11 '22 at 06:19
  • 2
    not really infinite that loop --`cout << s1.size() - s2.size() << endl;` – kikon Oct 11 '22 at 06:20
  • 4
    For gcc/clang, enable `-Wsign-compare` will give a warning of comparison between integers of different signs. – halfelf Oct 11 '22 at 06:21
  • 1
    ... I would recommend at least `-Wall -Wextra -pedantic -Werror`. – Quimby Oct 11 '22 at 06:24
  • 9
    Obligatory [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Chris Oct 11 '22 at 06:25
  • 1
    *"Even though `s1.size() - s2.size()` is under 0, the for loop does not finish"* -- To put this another way, **if** `s1.size() - s2.size()` was under 0, then the `for` loop would finish, right? And yet you observed that the `for` loop did not finish. So which premise would you like to bet on -- the one you assume with no supporting observations (did you stream `s1.size() - s2.size()` to `cout` to see what it is?), or the one that is supported by observations (the loop does not finish)? – JaMiT Oct 11 '22 at 06:37
  • Since size() gives you unsigned values and unsigned *cannot* be "under zero", your assumption is wrong... – U. W. Oct 11 '22 at 08:23
  • also [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/995714) – phuclv Oct 11 '22 at 09:33

0 Answers0