c – 当二进制运算符两边的签名不一致时,促销规则如何工作?

考虑以下程序:

// http://ideone.com/4I0dT
#include <limits>
#include <iostream>

int main()
{
    int max = std::numeric_limits<int>::max();
    unsigned int one = 1;
    unsigned int result = max + one;
    std::cout << result;
}

// http://ideone.com/UBuFZ
#include <limits>
#include <iostream>

int main()
{
    unsigned int us = 42;
    int neg = -43;
    int result = us + neg;
    std::cout << result;
}

运算符如何知道哪个是正确的返回类型?一般的规则是将所有参数转换成最广泛的类型,但是这里int和unsigned int之间没有明确的“获胜者”。在第一种情况下,unsigned int必须作为运算符的结果,因为我得到2147483648的结果。在第二种情况下,它必须选择int,因为我得到-1的结果。然而,在一般情况下,我看不出这是如何决定的。这个未定义的行为我看到还是别的什么?

这在§5/ 9中明确概述:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions shall be performed on both operands.
  • Then, if either operand is unsigned long the other shall be converted to unsigned long.
  • Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
  • Otherwise, if either operand is long, the other shall be converted to long.
  • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int]

在两种情况下,运算符的结果都是无符号的。因此,第二种情况是有效的:

int result = static_cast<int>(us + static_cast<unsigned>(neg));

因为在这种情况下,我们的否定值不能由int表示,所以结果的值是实现定义的 – §4.7/ 3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

http://stackoverflow.com/questions/6770258/how-do-promotion-rules-work-when-the-signedness-on-either-side-of-a-binary-opera

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c – 当二进制运算符两边的签名不一致时,促销规则如何工作?