c – 使用-1作为unsigned(size_t)类型的标志值
作者:互联网
我使用-1作为返回类型为size_t(无符号类型)的函数的标志值.
我一开始并没有注意到它,特别是因为它没有导致我的代码中的任何错误(我用x == -1,而不是x< 0检查它). 是否有任何微妙的原因我不应该留下它?什么时候这可能出乎意料?这是常用的吗? ptrdiff_t不太常见,输入时间较长,而且无论如何它都不是合适的类型,因为函数会将索引返回到数组中.
解决方法:
-1将始终转换为最大无符号值,这是由于4.7节积分转换:
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-3,twos-complement,c,d 来源: https://codeday.me/bug/20190916/1807026.html