Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 4294967295 (the highest number at 32bit) equal -1?

Tags:

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?

like image 552
Local Hero Avatar asked Dec 14 '22 13:12

Local Hero


2 Answers

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

like image 160
Sourav Ghosh Avatar answered Dec 23 '22 08:12

Sourav Ghosh


Because of the internal representation of negative numbers. This is called the two's complement.

like image 24
ikrabbe Avatar answered Dec 23 '22 07:12

ikrabbe