C++ 类型转换问题

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.

阅读 1.9k
1 个回答

文档现读现卖了,欢迎大佬指点。

隐式类型转换

对表达式 a + b

左右操作数会先做一个 integral promotion 提升到整型数据,然后遵循算数运算符的隐式转换规则转换:

  • 如果有一个操作数是 scoped enumeration type (就是 enum class 声明的枚举),不做转换,操作数必须是同样的类型
  • 如果有一个操作数是 long double ,另一个操作数也转换成 long double
  • 如果有一个操作数是 double,另一个操作数也转换成 double
  • 如果有一个操作数是 float,另一个操作数也转换成 float
  • 如果操作数都是 integer type (上一步 integral promotion 把 char 之类的类型都提升到了 integer 所以不会有别的类型)

    • 如果操作数都是 unsignd 或者 signed ,从低转换排名(conversion rank)向高转换排名转换
    • 如果 unsigned 操作数的转换排名大于等于 signed 操作数,则 signed 操作数转换为 unsigned 操作数类型
    • 如果 signed 操作数能表示 unsigned 操作数的所有值,则转换为 signed 操作数的类型
    • 都转换成 signed 操作数对应的 unsigned 类型。

转换排名conversion rank

  1. bool
  2. signed char
  3. short
  4. int
  5. long
  6. long long

无符号类型和上面的排名相同,char_t 之类的类型则看底层类型。


对于题中我假设为 unsigned int + long,用上述规则判断:

  • 没有 enum class
  • 没有 long double
  • 没有 double
  • 没有 float
  • 并不都是 unsigned/signed
  • unsigned 操作数排名低于 signed 操作数
  • long 不能表示 unsigned int 的所有值(假设 long 和 int 都是 32bit)
  • 以上情况都不满足,取 signed 类型对应的 unsigned 类型,long 的对应 unsigned 类型是 unsigned long

所以最终应该是操作数都隐式转换成 unsigned long 后计算。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题