-1u 有效吗?

发布于 2024-12-20 01:21:20 字数 206 浏览 2 评论 0原文

例如

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心的位置 2024-12-27 01:21:20

1u 的类型为 unsigned int。然后使用一元 - 运算符将其取反。行为如下:

无符号数量的负数是通过从 2n 中减去其值来计算的,其中 n 是提升的操作数中的位数 (C++11 5.3.1/8)。< /p>

因此,-1u 保证为您提供由 unsigned int 表示的最大值。

要获取任意无符号类型可表示的最大值,可以将 -1 转换为该类型。例如,对于 std::size_t,请考虑
static_cast(-1)

1u has the type unsigned int. This is then negated using the unary - operator. The behavior is as follows:

The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the promoted operand (C++11 5.3.1/8).

-1u is thus guaranteed to give you the largest value representable by unsigned int.

To get the largest value representable by an arbitrary unsigned type, you can cast -1 to that type. For example, for std::size_t, consider
static_cast<std::size_t>(-1).

难如初 2024-12-27 01:21:20

我一直使用 ~0U 来达到“无符号,所有位打开”的目的。

I've always used ~0U for the purpose of "unsigned, all bits on".

此生挚爱伱 2024-12-27 01:21:20

编译器实现相关的行为很烦人。不过,你应该能够做到这一点:

size_t x = 0;
x--;

if ((x+1) == 0)

Compiler implementation dependant behavior is annoying. You should be able to do this, though:

size_t x = 0;
x--;

if ((x+1) == 0)
感性不性感 2024-12-27 01:21:20

虽然这是技术上有效的代码,但您依赖于实现相关的行为:将负数转换为无符号的溢出处理。但是,如果您需要将 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.

梦旅人picnic 2024-12-27 01:21:20

这可能是您想要的:

size_t x = -1ull;

if (x == -((size_t)-1ull))
    ...

x 将被设置为可能的最大整数,这可能不是所有位都被设置。使用 ~0 来实现这一点。

This is likely what you want:

size_t x = -1ull;

if (x == -((size_t)-1ull))
    ...

x will be set to the largest integer possible, which may not be all bits set. Use ~0 for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文