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

社会主义新天地 提交于 2019-11-26 20:05:09

问题


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.


回答1:


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.




回答2:


#define MAZ_SZ (~(size_t)0)

or SIZE_MAX




回答3:


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



回答4:


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;



回答5:


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



来源:https://stackoverflow.com/questions/3472311/what-is-a-portable-method-to-find-the-maximum-value-of-size-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!