Standard way to determine max range of size_t?

M

Michael Ekstrand

I'm looking for a standard (or standard-ish) way to determine the maximum
value representable by a size_t. I can't seem to find anything
officially standard - cstddef doesn't seem to define such a thing, nor
does climits.

Applying grep to my /usr/include reveals an stdint.h header which defines
a SIZE_MAX, some further research indicates that this is a C99 standard
header but not standard for either C89 or standard C++. My primary target
compiler is G++, so that would be acceptable, but I would rather use a
standard means if one exists.

So, my question is: Is there a mechanism in standard C++ to determine the
maximum value of a size_t? If there is not a define or some other
declaration of this limit, is it reliable to assume that ((size_t) -1)
(or some more appropriate style of cast) is the maximum value which can be
stored in a size_t?

Thank you,
- Michael
 
M

mlimber

I'm looking for a standard (or standard-ish) way to determine the maximum
value representable by a size_t. I can't seem to find anything
officially standard - cstddef doesn't seem to define such a thing, nor
does climits.

Applying grep to my /usr/include reveals an stdint.h header which defines
a SIZE_MAX, some further research indicates that this is a C99 standard
header but not standard for either C89 or standard C++. My primary target
compiler is G++, so that would be acceptable, but I would rather use a
standard means if one exists.

So, my question is: Is there a mechanism in standard C++ to determine the
maximum value of a size_t? If there is not a define or some other
declaration of this limit, is it reliable to assume that ((size_t) -1)
(or some more appropriate style of cast) is the maximum value which can be
stored in a size_t?

Thank you,
- Michael

Yes. Include <limits>, then do:

std::numeric_limits<std::size_t>::max()

Cheers! --M
 
A

Andrew Koenig

I'm looking for a standard (or standard-ish) way to determine the maximum
value representable by a size_t.

(size_t)-1 should do it. The point is that size_t is guaranteed to be an
unsigned type, and a signed integer is converted to unsigned by taking it
modulo 2^n, where n is the number of bits in the unsigned type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top