C++ – Why does 4294967295 (the highest number at 32bit) equal -1

c

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?

Best Answer

  • 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.

  • In case, find is unsuccessful, it returns -1.

So, both are equal, in your case and the if is satisfied.

Now, to answer

name.npos instead, 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.