Home >Backend Development >C++ >How Do C Promotion Rules Handle Binary Operations with Signed and Unsigned Integers?

How Do C Promotion Rules Handle Binary Operations with Signed and Unsigned Integers?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 14:24:10530browse

How Do C   Promotion Rules Handle Binary Operations with Signed and Unsigned Integers?

Promotion Rules with Operators Handling Signed and Unsigned Integers

When dealing with binary operators involving different signedness between their operands, the promotion rules outlined in the C Standard come into play. These rules determine the resulting type of the operation and how the operands are converted.

Specifically, the "usual arithmetic conversions" apply here (§5/9). These conversions are ranked in descending precedence:

  1. Long double (if present)
  2. Double
  3. Float
  4. Integral promotions (convert short/int/long long to int/long/long long)
  5. Unsigned long (if present)
  6. Long if long int can represent all unsigned int values, or unsigned long int otherwise
  7. Long (if present)
  8. Unsigned (if present)

Applying these rules to the two scenarios presented:

Scenario 1:

int max = std::numeric_limits<int>::max();
unsigned int one = 1;
unsigned int result = max + one;
  • max is signed int, one is unsigned int
  • Integral promotions occur, resulting in max as int
  • Since unsigned int is ranked higher, the result type is unsigned int
  • Result: unsigned overflow to 2147483648

Scenario 2:

unsigned int us = 42;
int neg = -43;
int result = us + neg;
  • us is unsigned int, neg is signed int
  • Integral promotions occur, resulting in us as unsigned int, neg as int
  • Since unsigned int is ranked higher, the result type is unsigned int
  • However, the value of us neg (-1) is not representable in int
  • Result: Implementation-defined behavior, likely returning -1 or platform-dependent

The above is the detailed content of How Do C Promotion Rules Handle Binary Operations with Signed and Unsigned Integers?. For more information, please follow other related articles on the PHP Chinese website!

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