JoshuaYang's blog

By JoshuaYang, history, 16 months ago, In English

Let's look at a simple block of code, specifically the conditional statement in the for loop

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

int main() {
    string s = "123";
    string s2 = "12332";
    for (int i=0; i<(s.size()-s2.size()); ++i) {
        cout << "WTF";
    }
}

You expect the for loop to not even run because s.size()-s2.size() is -2, right? Well turns out since size() or .length() is returned as an unsigned integer (makes sense in retrospect), when c++ executes s.size() - s2.size(), you end with a large positive integer ( specifically 18446744073709551614) due to overflow because unsigned integers cannot be negative.

Something FYI I learned today after debugging for ~30 min and thought was interesting to share. Peace out, JY out.

Full text and comments »

  • Vote: I like it
  • +18
  • Vote: I do not like it