2

Not a duplicate of C++ for loop continue to loop even though it shouldn't

I found out that for loop continues even though the conditions are false. An example is here

int isSubstring(std::string s1, std::string s2)
{
    for (int i = 0; i < s2.size() - s1.size(); i++) {
        
    }
    return -1;
}

If I call it like isSubtring("abcd", "a"); it should've returned -1 right? But it doesn't. In Visual Studio debugger I saw the value of i goes up forever. But, if call this

for (int i = 0; i < -3; i++) {
        std::cout << "\ni=" << i;
    }

It behaves as intended. This also applies for while loop. My question is, why is that?

Edit: removed unnecessary code

Ryazack
  • 21
  • 2
  • 2
    [Beware](https://stackoverflow.com/questions/5416414/signed-unsigned-comparisons) of mixing signed and unsigned types. `size()` returns a value of unsigned type. `a.size() - b.size() >= 0` is **always** true. – Evg Mar 28 '21 at 09:20
  • `cout << s2.size() - s1.size() << endl;` returns a large number. You should fix your types. – NanoBit Mar 28 '21 at 09:22
  • 1
    A `std::string`'s `size()` member returns an unsigned type, and subtracting unsigned values gives an unsigned value. The condition in your code of `i < s2.size() - s1.size()` will never end if `s1.size() > s2.size()`, since `s2.size() - s1.size()` will give a large positive value. For example, if `s2.size()` is zero and `s1.size()` is `1`, the `s2.size() - s1.size()` will give typically give a value equal to `std::numeric_limits::max()` (assuming that the return type of `size()` is `std::size_t`, which is common in practice, albeit not guaranteed). – Peter Mar 28 '21 at 09:28
  • Please compile your program with `-Wall` (all warnings enabled), fix those warnings and _then_ see if the problem still exists. – Zoso Mar 28 '21 at 09:30
  • Thamk you @Evg . Should I do this? `i < (int)s2.size() - (int)s1.size()` – Ryazack Mar 28 '21 at 09:32
  • @Ryazack - Only if you want undefined behaviour if `s2.size()` or `s1.size()` are larger than can be stored in an `int`. – Peter Mar 28 '21 at 09:34
  • @Ryazack, `std:ptrdiff_t` would be a better choice. – Evg Mar 28 '21 at 09:37

0 Answers0