简体   繁体   English

这段代码在做什么? (为size_t)-1-

[英]What is this code doing? (size_t)-1

Can someone explain what happens when size_t, or any other type identifier, is wrapped in parentheses. 有人可以解释当size_t或任何其他类型标识符包含在括号中时会发生什么。 I know it is the old typecast syntax but in this context I don't follow what is happening. 我知道这是旧的类型转换语法,但在这种情况下,我不会关注正在发生的事情。

I've seen it for defining the max size of a type as: 我已经看到它将类型的最大大小定义为:

size_t max_size = (size_t)-1

This code (unnecessarily) casts -1 to size_t . 此代码(不必要地)将-1转换为size_t The most probable intent was getting the largest possible value of size_t on this system. 最可能的意图是在此系统上获得size_t的最大可能值。

Although this code doesn't have Undefined Behavior, this code is ugly - in C++ you should use std::numeric_limits<size_t>::max() and in C use SIZE_MAX macro for exactly a purpose of getting the largest size_t value. 虽然这段代码没有未定义的行为,但这段代码很难看 - 在C ++中你应该使用std::numeric_limits<size_t>::max()而在C中使用SIZE_MAX宏来获得最大的size_t值。

(size_t)-1 is in fact the equivalent of size_t(-1) (size_t)-1实际上相当于size_t(-1)

See also the following question c cast syntax styles 另请参阅以下问题c cast语法样式

Some library methods intentionally return (size_t)(-1) to indicate an error condition. 某些库方法有意返回(size_t)(-1)以指示错误情况。 For example, the iconv method from the GNU libiconv library . 例如, GNU libiconv库中的iconv方法 I assume there is some good reason why these functions don't return ssize_t (signed) return values, which would allow you to check for -1 directly. 我假设有一些很好的理由为什么这些函数不返回ssize_t (signed)返回值,这将允许您直接检查-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM