I have this simple part of my code:
int pch = name.find("#");
if(pch == name.npos) continue;
When in name.find doesn't find "#", pch is equal to -1. name.npos instead, if I print it, is 4294967295. Why is it that in this case, when pch is -1 and name.npos is 4294967295, the program enters the if condition?
string::npos denotes that the position is not found. It is usually represented by a constant value of -1.Reference
This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
find is unsuccessful, it returns -1.So, both are equal, in your case and the if is satisfied.
Now, to answer
name.nposinstead, if I print it, is 4294967295
because, string::npos is of type size_t which is usually typedef to unsigned type. The -1,which is used to initialize an unsigned type will be stored as and printing the maximum possible unsigned value.
Because of the internal representation of negative numbers. This is called the two's complement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With