Aman Deep Gautam
Aman Deep Gautam

Reputation: 8747

Printing negative numbers created on the fly gives incorrect output in c++

Following code explains a quirk, and I am unable to understand why it is the way it is. The comments in the code explain the quirk:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string a,b;
    a = "abc";
    b = "def";
    // On the fly calculation of diff does not lead to desirable results.
    cout<<"a size: "<<a.size()<<" b size: "<<b.size()<<" diff: "<<a.size()-b.size()-1<<endl;
    // Following assignment works as expected.
    int diff = a.size()-b.size()-1;
    cout<<"diff "<<diff<<endl;
    for (int i=a.size()-1; i>a.size()-b.size()-1; --i) {
        cout<<"running"<<endl;
    }
    return 0;
}

Here is the output I get:

a size: 3 b size: 3 diff: 4294967295
diff: -1

Upvotes: 0

Views: 68

Answers (1)

rocambille
rocambille

Reputation: 15966

a.size()-b.size()-1

Since the size method returns a size_t, i.e. an unsigned value, you're computing 3-3-1 = -1 in an "unsigned space" which gives you a wrong value.

Try:

int(a.size())-int(b.size())-1

Upvotes: 5

Related Questions