8
votes

What do people use to denote that size_t is invalid? -1 does not work, and 0 can be a valid size.

5
How does -1 "not work"?Keith Thompson
Personally, I refuse to use non-POSIX systems and I rely on ssize_t being available.user529758

5 Answers

10
votes

Perhaps ((size_t)-1)?

Strictly speaking, it is a valid size, but once you have this one you're not likely to need any other ;-)

4
votes

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.

3
votes

Basically you can not. Whatever value you use might be a valid one. Better pass a flag saying that it is invalid.

1
votes

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.

1
votes

My version is:

#include <limits>
#define invalid_index std::numeric_limits<size_t>::max()