如何根据操作数的类型决定结果的类型?

How the type of the result is decided based on type of operand?

如果我们有

   int a = 1;
   unsigned int b = -1;

表达式的类型是什么

a + b;

我可以使用 int 来存储结果吗?

对于您的代码,"usual arithmetic conversions" 规则将适用于 + 运算符的操作数,因此,对于

  a + b;

根据整数提升规则,a 将在加法前提升为 unsigned int。结果也将是 unsigned int.

类型

引用 C11 标准,章节 §6.3.1.8

..[..]... 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.

有一组称为常用算术转换 的规则,用于指定在使用算术运算符时应用的转换。 (如果您在这里搜索该词,您会很容易找到完整列表)

在这种情况下,int 被提升为 unsigned int,保留值 1,因此加法的结果明确定义为 (unsigned int)0 .

由于此值不大于INT_MAX,您可以将其存储在int中。

表达式类型

a + b;

将是unsigned int

根据 C 标准 )6.3.1.8 通常的算术转换)

2...Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type

至于将无符号类型的对象赋值给与您的示例具有相同等级的有符号类型的对象,那么(C标准,6.3.1.3有符号和无符号整数)id有符号整数类型的对象可以不代表无符号整型对象的值 then

3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised

如果该值可以由签名对象表示,则它会原封不动地存储在签名对象中。