添加有符号和无符号值时,我们遵循这两条规则(来自 https://stackoverflow.com/a/2280810/1073672 )
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
上述哪些规则将被触发:
unsigned int ui = 4;
ui = ui + 532;
最佳答案
常量的类型532
是 int
,已签名。
查看第一条规则,从unsigned int
开始和int
具有相同的等级,则无符号类型的等级大于或等于有符号类型的等级。第一条规则匹配。签名532
转换为unsigned int
添加之前。
即使第一条规则不匹配,添加也无法匹配第二条规则,因为签名 int
无法表示 unsigned int
的所有值。 (可能的带符号 int
与 unsigned int
的数量相同,但例如, -1
是带符号 int
但不是 unsigned int
,因此必须至少有一个 unsigned int
不能表示为带符号的 int
。)
关于c - 具有有符号和无符号整数的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725982/