How Promotion Rules Govern Binary Operator Arithmetic with Mixed Sign Types
Consider the following code:
int max = std::numeric_limits<int>::max(); unsigned int one = 1; unsigned int result = max + one;
The operator calculates result as 2147483648, suggesting unsigned int as its return type. Conversely, in the following code:
unsigned int us = 42; int neg = -43; int result = us + neg;
result is -1, indicating an int return type.
Promotion Rule Resolution
The C standard defines specific promotion rules for arithmetic binary operators (C §5/9):
Implications for the Examples
In both examples, the promotion rules result in an unsigned type for the operator calculation.
Example 1: Both max and one are promoted to unsigned int, resulting in a return type of unsigned int.
Example 2: The promotion rules do not dictate a clear winner between int and unsigned int. However, the unsigned type is selected, leading to an unsigned overflow for result. Since result is ultimately assigned to an int, the resulting value is undefined per C §4.7/3.
The above is the detailed content of How Do C Promotion Rules Determine the Return Type of Binary Arithmetic Operators with Mixed Signed and Unsigned Integer Types?. For more information, please follow other related articles on the PHP Chinese website!