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.
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.
A manifest constant (a macro) exists in C99 and it is called SIZE_MAX
. There's no such constant in C89/90.
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.
Would something along the lines of (1 << sizeof(size_t)) - 1
work? (Untested, and possibly a language-lawyer reason this won't work...).
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 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;