"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do Usual Arithmetic Conversions Determine the Result Type of Binary \"+\" Operators with Signed and Unsigned Operands?

How Do Usual Arithmetic Conversions Determine the Result Type of Binary \"+\" Operators with Signed and Unsigned Operands?

Published on 2024-12-22
Browse:133

How Do Usual Arithmetic Conversions Determine the Result Type of Binary \

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:

  • long double, both operands are converted to long double.
  • double, both operands are converted to double.
  • float, both operands are converted to float.
  • unsigned long, the other operand is converted to unsigned long.
  • long int and the other operand unsigned int, both operands are converted to unsigned long int if the value of the unsigned int can be represented in a long int; otherwise, both are converted to long.
  • long, the other operand is converted to long.
  • unsigned, the other operand is converted to unsigned.

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.

Latest tutorial More>

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