查找 size_t 最大值的可移植方法是什么?
我想知道我的程序正在运行的系统上 size_t 的最大值。 我的第一直觉是使用负数 1,如下所示:
size_t max_size = (size_t)-1;
但我猜有更好的方法,或者在某处定义的常量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C99 中存在一个明显常量(宏),称为
SIZE_MAX
。但 C89/90 中没有这样的常数。但是,您在原始帖子中拥有的是一种完美可移植的方法来查找
size_t
的最大值。它保证适用于任何无符号类型。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.或
SIZE_MAX
or
SIZE_MAX
作为其他答案中建议的位操作的替代方案,您可以这样做:
As an alternative to bit-operations suggested in the other answers, you could do this:
OP建议的
size_t max_size = (size_t)-1;
解决方案绝对是迄今为止最好的,但我确实找到了另一种更复杂的方法来做到这一点。我发布它只是出于学术好奇心。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.如果您假设至少是 C++11 编译器,则 SIZE_MAX 应该可供您使用:
http ://en.cppreference.com/w/c/types/limits
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
而不是:
我会使用:
更清楚的是,您构建了值为 -1 的 size_t 并且没有从名为“size_t”的假设变量中减去 -1 :-D
Instead of:
I would use:
It's just a bit more clear that you constructing a size_t with value -1 and are not subtracting -1 from a hypothetical variable called "size_t" :-D