Home >Backend Development >C++ >How Does C Handle Binary Operator Promotion with Differing Signedness?
Binary Operator Promotion When Sign Differ
When binary operators operate on operands with differing signedness, the C standard provides specific guidelines for determining the promotion rules and the resulting type.
Section 5/9 of the standard outlines the "usual arithmetic conversions" that apply to such operators. These conversions follow a hierarchical order:
Applying these rules to the provided code examples:
Example 1:
unsigned int one = 1; int max = std::numeric_limits<int>::max(); unsigned int result = max + one;
Since unsigned int takes precedence over int in step 5 of the rules, all operands are converted to unsigned int. Hence, result is of type unsigned int.
Example 2:
unsigned int us = 42; int neg = -43; int result = us + neg;
In this case, the rules dictate that both operands should be converted to unsigned int. However, the resulting value (-1) cannot be represented in unsigned int. Therefore, the result type of the expression is implementation-defined according to §4.7/3.
The above is the detailed content of How Does C Handle Binary Operator Promotion with Differing Signedness?. For more information, please follow other related articles on the PHP Chinese website!