什么时候一个整数的符号性真的重要吗? [英] When does the signedness of an integer really matter?
本文介绍了什么时候一个整数的符号性真的重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于转换和操作都在C中定义的方式,它似乎很少不管您是否使用符号或无符号变量:
Due to the way conversions and operations are defined in C, it seems to rarely matter whether you use a signed or an unsigned variable:
uint8_t u; int8_t i;
u = -3; i = -3;
u *= 2; i *= 2;
u += 15; i += 15;
u >>= 2; i >>= 2;
printf("%u",u); // -> 2
printf("%u",i); // -> 2
那么,有没有一套规则,告诉在什么条件下一个变量的符号性真的有差别?
So, is there a set of rules to tell under which conditions the signedness of a variable really makes a difference?
推荐答案
它的问题在这些背景:
- 除法和模数:
-2/2 = 1
,-2U / 2 = UINT_MAX / 2-1
,-3%4 = -3
,-3u%4 = 1
- 的变化。对于负符号值,
&GT的结果;>
和<<
是实现定义或定义,RESP 。对于无符号的价值,他们总是定义。 - relationals
-2< 0
,-2U> 0
- 溢出。
X + 1> X
可通过编译器假设总是正确的当且仅当的X
签署类型。
- division and modulo:
-2/2 = 1
,-2u/2 = UINT_MAX/2-1
,-3%4 = -3
,-3u%4 = 1
- shifts. For negative signed values, the result of
>>
and<<
are implementation defined or undefined, resp. For unsigned values, they are always defined. - relationals
-2 < 0
,-2u > 0
- overflows.
x+1 > x
may be assumed by the compiler to be always true iffx
has signed type.
这篇关于什么时候一个整数的符号性真的重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文