0

The following code prints count as 0. But s.length() is 11 so shouldn't count be 10011?

int main() {
    clock_t start_time = clock();
    string s = "hello world";
    int count = 0;
    for (int i = -10000; i < s.length(); i++) {
        count++;
    }
    cout << count << endl;
    cout << clock() - start_time;
    return 0;
}
wannabe
  • 131
  • 1
  • 2
  • 8

1 Answers1

0

You are running into a typical signed-vs-unsigned comparison failure - one of the frequently asked questions on SO (see Comparison operation on unsigned and signed integers for one example).

You can fix your code by switching to equality comparison instead of relational comparison

for (int i = -10000; i != s.length(); i++)

or by forcing signed integer comparison

for (int i = -10000; i < (int) s.length(); i++)

(although in the latter case you are limiting the range of possible lengths without a good reason).

But in general it is a good idea to avoid mixing signed and unsigned types in comparisons. Redesign your code to avoid it.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • I think that the comment made by @Someprogrammerdude is in fact the best answer in this case, or more accurately, implies what the actual problem "behind the scene" is (i.e., what's wrong with the OP's way of thinking). The `-10000` should be moved from the initial value into the condition itself, i.e., `i – barak manos Dec 25 '16 at 06:55
  • In addition to all of that - though I'm personally not "harsh" on this kind of issue but many users here are - since the question is tagged C++, you may want to replace that C-style cast with `static_cast`... – barak manos Dec 25 '16 at 06:56
  • @barak manos: I don't see it as an issue at all. I believe that in C++ code `static_cast` should be reserved to pointer casts: hierarchical up-casts and casts from `void *`. Arithmetic casts should be expressed by C-style casts, exactly as I did above. – AnT stands with Russia Dec 25 '16 at 07:47
  • I thought the same, which is why I posted [this question](http://stackoverflow.com/q/27525577/1382251). I still generally agree with you, but I got some interesting answers to that question, which you might want to have a look at. – barak manos Dec 25 '16 at 07:50
  • @barak manos: As for the "best answer"... the code is too abstract to allow any meaningful decision about what is the "best" solution in this case. Until the OP provides a detailed explanation of the context that led them to this strange cycle, there's no way to say what solution is the "best" here. But I don't believe there is any meaningful context here. The code appears to be a contrived experiment. For a code like that trying to prove that one solution is better than the other is rather pointless endeavor. – AnT stands with Russia Dec 25 '16 at 07:51