Just a quick question, if string::npos represents the largest possible value for a string object, how can this value be -1 if it's an unsigned integer?
I know this value will change for different compilers, as string::npos on my compiler is set to 4,294,967,295 which makes sense but I don't understand how -1 can represent the largest value.

Thanks in advance

When you overflow or underflow an unsigned type, wrap-around occurs. Due to unsigned wrap-around, -1 becomes the largest unsigned value for the type. One common trick is taking advantage of that effect for decrementing loops on an unsigned counter without having to know the actual range of the type:

for (std::size_t i = n; i < (size_t)-1; i--) {
    // ...
}

Because it is an unsigned integer, shouldn't it only be able to store positive values, like when it wraps around wouldn't the value now be 0?
Or is the -1 just like a catch all method, so that nothing else can possibly have that value?

>Because it is an unsigned integer, shouldn't it only be able to store positive values
Yes, that's it exactly.

>Or is the -1 just like a catch all method, so that nothing else can possibly have that value?
If it helps, you can think of -1 in unsigned context as (0U - 1) . The effect is the same: subtracting 1 from 0 underflows and wraps around to the largest value for unsigned int.

I think I understand...
So is the -1 used to represent the maximum value for any compiler, as they will be different?

-1 in an unsigned context is portable, yes.

Ok thanks for your help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.