Home > Backend Development > C++ > How Does C Handle Binary Operator Promotion with Differing Signedness?

How Does C Handle Binary Operator Promotion with Differing Signedness?

Mary-Kate Olsen
Release: 2024-12-02 08:00:13
Original
923 people have browsed it

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:

  1. If either operand is long double, both operands are converted to long double.
  2. If either operand is double, both operands are converted to double.
  3. If either operand is float, both operands are converted to float.
  4. Integral promotions are performed on both operands.
  5. If either operand is unsigned long, both operands are converted to unsigned long.
  6. If one operand is long int and the other is unsigned int, determine if long int can represent all values of unsigned int. If so, convert unsigned int to long int; otherwise, convert both operands to unsigned long int.
  7. If either operand is long, both operands are converted to long.
  8. If either operand is unsigned, both operands are converted to unsigned.
  9. Otherwise, both operands remain of type int.

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

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

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!

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