Surfer
Surfer

Reputation: 121

std::string.size() unknown behavior

I expected Output 1 to be equal to Output 2, because of simple addition and subtraction, the bracket's should make no difference
Here's the Output:

Output 1: 3
Output 2: 4294967295
Output 1: 6
Output 2: 2

I think it's something about the string.size(), but I can't explain to myself how this may happen. Maybe someone can help me understand this.

int lastPos = 0;
std::string inputString = "0b1*10*0";
while (lastPos != -1){
    lastPos = inputString.find('*',lastPos+1);

    if(lastPos != -1){
        // -2 for 0b/ removal
        // 8 Bit max Size
        std::cout << "Output 1: " << lastPos-2 + 8 - (inputString.size()-2) << std::endl;
        std::cout << "Output 2: " << lastPos-2 + 8 - inputString.size()-2 << std::endl;
    }          
}

Upvotes: 0

Views: 116

Answers (1)

rustyx
rustyx

Reputation: 85266

lastPos-2 + 8 - (inputString.size()-2) != lastPos-2 + 8 - inputString.size()-2

lastPos-2 + 8 - (inputString.size()-2) == lastPos-2 + 8 - inputString.size()+2

Because -(-2) == +2

Upvotes: 4

Related Questions