简体   繁体   中英

Invalid Value for size_t

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

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 ;-)

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.

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

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.

My version is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM