What is a portable method to find the maximum value of size_t?

CSize T

C Problem Overview


I'd like to know the maximum value of size_t on the system my program is running. My first instinct was to use negative 1, like so:

size_t max_size = (size_t)-1;

But I'm guessing there's a better way, or a constant defined somewhere.

C Solutions


Solution 1 - C

A manifest constant (a macro) exists in C99 and it is called SIZE_MAX. There's no such constant in C89/90 though.

However, what you have in your original post is a perfectly portable method of finding the maximum value of size_t. It is guaranteed to work with any unsigned type.

Solution 2 - C

#define MAZ_SZ (~(size_t)0)

or SIZE_MAX

Solution 3 - C

As an alternative to bit-operations suggested in the other answers, you could do this in C++

#include <limits>
size_t maxvalue = std::numeric_limits<size_t>::max()

Solution 4 - C

The size_t max_size = (size_t)-1; solution suggested by the OP is definitely the best so far, but I did figure out another, more convoluted, way to do this. I'm posting it just for academic curiosity.

#include <limits.h>

size_t max_size = ((((size_t)1 << (CHAR_BIT * sizeof(size_t) - 1)) - 1) << 1) + 1;

Solution 5 - C

If you are assuming at least C++11 compiler then SIZE_MAX should be available to you:

http://en.cppreference.com/w/c/types/limits

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJusticleView Question on Stackoverflow
Solution 1 - CAnTView Answer on Stackoverflow
Solution 2 - CnategooseView Answer on Stackoverflow
Solution 3 - CkalmiyaView Answer on Stackoverflow
Solution 4 - CPraetorianView Answer on Stackoverflow
Solution 5 - CShital ShahView Answer on Stackoverflow