C++ Primer 5th 读到这一段,这里比较疑惑,如果long和unsigned int 具有同样的大小,那么long就转成unsigned int, 判断标准不是指出如果unsigned 类型可以填进更大类型就转换unsigned 到 signed类型吗? 这里在同样大小的情况下,unsigned int 不能转换成long?
The remaining case is when the signed operand has a larger type than the unsigned operand. In this case, the result is machine dependent. If all values in the unsigned type fit in the larger type, then the unsigned operand is converted to the signed type. If the values don’t fit, then the signed operand is converted to the unsigned type. For example, if the operands are long and unsigned int, and int and long have the same size, the long will be converted to unsigned int. If the long type has more bits, then the unsigned int will be converted to long.
文档现读现卖了,欢迎大佬指点。
隐式类型转换
对表达式
a + b
左右操作数会先做一个 integral promotion 提升到整型数据,然后遵循算数运算符的隐式转换规则转换:
enum class
声明的枚举),不做转换,操作数必须是同样的类型long double
,另一个操作数也转换成long double
double
,另一个操作数也转换成double
float
,另一个操作数也转换成float
如果操作数都是 integer type (上一步 integral promotion 把 char 之类的类型都提升到了 integer 所以不会有别的类型)
转换排名conversion rank
bool
signed char
short
int
long
long long
无符号类型和上面的排名相同,char_t 之类的类型则看底层类型。
对于题中我假设为
unsigned int + long
,用上述规则判断:所以最终应该是操作数都隐式转换成
unsigned long
后计算。