C语言 什么是找到size_t最大值的便携方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3472311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a portable method to find the maximum value of size_t?
提问by Justicle
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 的最大值。我的第一直觉是使用负 1,如下所示:
size_t max_size = (size_t)-1;
But I'm guessing there's a better way, or a constant defined somewhere.
但我猜有更好的方法,或者在某处定义一个常量。
采纳答案by AnT
A manifest constant (a macro) exists in C99 and it is called SIZE_MAX. There's no such constant in C89/90 though.
C99 中存在一个清单常量(一个宏),它被称为SIZE_MAX. 但是在 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.
但是,您在原始帖子中拥有的是一种完美可移植的方法,可以找到size_t. 它保证适用于任何无符号类型。
回答by nategoose
#define MAZ_SZ (~(size_t)0)
or SIZE_MAX
或者 SIZE_MAX
回答by kalmiya
As an alternative to bit-operations suggested in the other answers, you could do this in C++
作为其他答案中建议的位操作的替代方法,您可以在 C++ 中执行此操作
#include <limits>
size_t maxvalue = std::numeric_limits<size_t>::max()
回答by Praetorian
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.
size_t max_size = (size_t)-1;OP 提出的解决方案绝对是迄今为止最好的解决方案,但我确实想出了另一种更复杂的方法来做到这一点。我发布它只是为了学术好奇。
#include <limits.h>
size_t max_size = ((((size_t)1 << (CHAR_BIT * sizeof(size_t) - 1)) - 1) << 1) + 1;
回答by Shital Shah
If you are assuming at least C++11 compiler then SIZE_MAX should be available to you:
如果您假设至少是 C++11 编译器,那么 SIZE_MAX 应该可供您使用:

