What do people use to denote that size_t is invalid? -1 does not work, and 0 can be a valid size.
5 Answers
If you're talking about std::string, then size_t's invalid value is std::string::npos. Normally you shouldn't use -1 because a size_t is unsigned, and you can get failed comparisons on a compiler doing implicit conversions between types.
That being said, std::strings's npos is set to 0XFFFFFFFFFFFFFFFF... which is the binary equivallent of -1. It also evaluates to the maximum allowed value for an unsigned size_t field.
And what do you do to denote that an int
is invalid? -1 is a valid value for an int. These types don't have designated "invalid" values. You can decide to choose a certain value (that can never normally be the value of what your variable represents) to represent an illegal value, but that is your own definition, and not something that people generally use.
Personally, I don't like this way. I prefer to create another variable, bool IsValid
, which will say, whether the value of that size_t variable is valid. Sometimes, it may even be better to create a class to encapsulate them.
ssize_t
being available. – user529758