Java
Java

Reputation: 43

string::length returns false value?

string str = "abcdef";
cout << str.length() << endl; //6
cout << str.length() - 7 << endl; //4294967295

I don't understand why str.length() - 7 returned 4294967295 instead of -1.

Could you help me to explain this?

Upvotes: 1

Views: 253

Answers (2)

gsamaras
gsamaras

Reputation: 73444

The return type of str.length() is size_t:

size_t length() const noexcept;

you can think about it as an unsigned int for this case.

The unsigned integer underflows when it gets to a negative value, wraps around and goes to other extreme, causing you, to see in your system 4294967295.

4294967295 (2^32 - 1) corresponds to the maximum value of a 32-bit unsigned type - which is consistent with a fair few 32-bit implementations. Moreover size_t can be, but is not required to be, a 32-bit type.

Upvotes: 6

Cuber
Cuber

Reputation: 713

str.length() returns a size_t, which is unsigned. This unsigned result wraps around and that is why you get 4294967295 instead of -1.

Upvotes: 8

Related Questions