简体   繁体   English

为什么 ptrdiff_t 签名?

[英]Why is ptrdiff_t signed?

If ptrdiff_t were unsigned, it would be able to refer to twice as many elements.如果ptrdiff_t是无符号的,它将能够引用两倍的元素。 On my machine PTRDIFF_MAX is expanded to 9223372036854775807i64 , whereas ULLONG_MAX is 18446744073709551615Ui64 .在我的机器上PTRDIFF_MAX扩展到9223372036854775807i64 ,而ULLONG_MAX18446744073709551615Ui64

I know that these values are huge themselves, but if我知道这些价值本身是巨大的,但如果

The type ( ptrdiff_t )'s size is chosen so that it can store the maximum size of a theoretically possible array of any type.选择类型 ( ptrdiff_t ) 的大小,以便它可以存储理论上可能的任何类型数组的最大大小。

ref 参考

then doesn't making it unsigned make more sense?那么让它未签名不是更有意义吗?

If ptrdiff_t were unsigned, it would be able to refer to twice as many elements.如果ptrdiff_t是无符号的,它将能够引用两倍的元素。

That is not correct.这是不正确的。 Making a type unsigned does not magically increase the amount of information it can hold.使类型无符号不会神奇地增加它可以容纳的信息量。 Signed and unsigned integers of the same size have exactly the same number of different states.相同大小的有符号和无符号整数具有完全相同数量的不同状态。 In the signed version, half the states represent negative numbers.在签名版本中,一半的状态表示负数 And you do need negative numbers to handle the result of subtracting a pointer with a higher address value from one with a lower address value.而且您确实需要负数来处理从具有较低地址值的指针中减去具有较高地址值的指针的结果。 For instance:例如:

int arr[42];
int* p1 = arr;
int* p2 = arr + 42;
auto diff = p1 - p2; // what should the result be?

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

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