c++ - 使用 -1 作为无符号 (size_t) 类型的标志值

标签 c++ c d twos-complement

我使用 -1 作为返回类型为 size_t(无符号类型)的函数的标志值。

一开始我没有注意到它,特别是因为它没有在我的代码中造成任何错误(我用 x == -1 来检查它,而不是 x < 0)。

有什么微妙的原因我不应该保持原样吗?这什么时候可能会出乎意料?这个常用吗?

ptrdiff_t 不太常见,需要更长的输入时间,而且它并不是真正合适的类型,因为该函数返回数组的索引。

最佳答案

-1 将始终转换为最大无符号值,这是由于 4.7 Integral conversions 部分:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

C99 的相同引用来自 6.3.1.3:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.49)

所以我们最终得到:

-1 + (UMAX + 1)

即:

UMAX

关于c++ - 使用 -1 作为无符号 (size_t) 类型的标志值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801069/

相关文章:

c++ - STL 容器的奇怪行为(构造/销毁和范围)

c - 在 C 中保留 RAM

c - Malloc 段错误

c - Linux 下的 Getopt

arrays - 如何创建一个具有设定大小但未设定值的数组?

c++ - postblit 构造函数与复制构造函数仅在源上有所不同吗?

python - 将多态对象从 C++ 传递给 python 函数

c++ - 代码工作正常,但我无法理解它打印的内容

c++ - 在 C++98/C++03 中,如何设置我的类,使其不能从中继承?

c# - 无法将指针数组放入 C# 中的不安全结构的根本原因是什么?