什么是求 size_t 的最大值的可移植方法?

我想知道 size _ t 在我的程序正在运行的系统上的最大值。 我的第一反应是使用负1,像这样:

size_t max_size = (size_t)-1;

但我猜还有更好的方法,或者在某处定义一个常数。

39128 次浏览

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.

#define MAZ_SZ (~(size_t)0)

or SIZE_MAX

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;

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

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