Promotion Rules for Signed and Unsigned Binary Operators
Consider the following code snippets:
// Snippet 1 int max = std::numeric_limits::max(); unsigned int one = 1; unsigned int result = max one;
// Snippet 2 unsigned int us = 42; int neg = -43; int result = us neg;
How does the " " operator determine the correct result type in these cases, given the differing signedness of the operands?
The operator follows the "usual arithmetic conversions" rule, which dictates the type conversion steps based on the operand types. According to this rule, if either operand is:
Since int and unsigned int are interchangeable in the rule, the operand with the wider type (unsigned int) is chosen as the result type.
This explains why in Snippet 1, the result is unsigned int (2147483648) and in Snippet 2, the result is int (-1). The signed operand (neg) is implicitly converted to unsigned int, resulting in an undefined value in the latter case.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3