Home > Backend Development > C++ > How Do C Promotion Rules Determine the Return Type of Binary Arithmetic Operators with Mixed Signed and Unsigned Integer Types?

How Do C Promotion Rules Determine the Return Type of Binary Arithmetic Operators with Mixed Signed and Unsigned Integer Types?

Patricia Arquette
Release: 2024-11-28 08:30:11
Original
862 people have browsed it

How Do C   Promotion Rules Determine the Return Type of Binary Arithmetic Operators with Mixed Signed and Unsigned Integer Types?

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;
Copy after login

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;
Copy after login

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):

  1. If either operand is long double, convert both to long double.
  2. If either operand is double, convert both to double.
  3. If either operand is float, convert both to float.
  4. Apply integral promotions to both operands.
  5. If either operand is unsigned long, convert both to unsigned long.
  6. If either operand is long int and the other unsigned int, convert the unsigned int to long int if possible, otherwise convert both to unsigned long int.
  7. If either operand is long, convert both to long.
  8. If either operand is unsigned, convert both to unsigned.
  9. If both operands are int, no further conversions occur.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template