-1u 有效吗?
例如
size_t x = -1u;
if (x == -1u)
...
有效吗?
如果这是有效的,它将阻止警告。 当然,在 32 位系统上 x 应该是 0xffffffff,在 64 位系统上 x 应该是 0xffffffff 系统应该是0xffffffffffffffff。
-约亨
Is for example
size_t x = -1u;
if (x == -1u)
...
valid?
If this is valid it would prevent a warning.
of course on a 32 bit system x should be 0xffffffff and on a 64 bit
system it should be 0xffffffffffffffff.
-Jochen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
1u
的类型为unsigned int
。然后使用一元-
运算符将其取反。行为如下:因此,
-1u
保证为您提供由unsigned int
表示的最大值。要获取任意无符号类型可表示的最大值,可以将
-1
转换为该类型。例如,对于std::size_t
,请考虑static_cast(-1)
。1u
has the typeunsigned int
. This is then negated using the unary-
operator. The behavior is as follows:-1u
is thus guaranteed to give you the largest value representable byunsigned int
.To get the largest value representable by an arbitrary unsigned type, you can cast
-1
to that type. For example, forstd::size_t
, considerstatic_cast<std::size_t>(-1)
.我一直使用 ~0U 来达到“无符号,所有位打开”的目的。
I've always used ~0U for the purpose of "unsigned, all bits on".
编译器实现相关的行为很烦人。不过,你应该能够做到这一点:
Compiler implementation dependant behavior is annoying. You should be able to do this, though:
虽然这是技术上有效的代码,但您依赖于实现相关的行为:将负数转换为无符号的溢出处理。但是,如果您需要将 size_t 与 -1 进行有意义的比较,因为您正在使用的 API 调用需要它,则系统已经搞砸了,但您的代码可能会工作,因为它们必须在另一侧执行相同的操作API 的。
While this is technically valid code, you are depending on implementation dependent behavior: overflow handling of converting a negative number to unsigned. However, if you need to meaningful compare a size_t with -1 because the API calls you are using require it, the system is already screwed up but your code is likely to work because they would have had to do the same thing on the other side of the API.
这可能是您想要的:
x
将被设置为可能的最大整数,这可能不是所有位都被设置。使用 ~0 来实现这一点。This is likely what you want:
x
will be set to the largest integer possible, which may not be all bits set. Use ~0 for that.