﻿ c – 当二进制运算符两边的签名不一致时,促销规则如何工作？ - 代码日志

#### 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;
}
``````

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));
``````

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