Home >Backend Development >C++ >What Happens When You Assign a Negative Value to an Unsigned Variable in C ?

What Happens When You Assign a Negative Value to an Unsigned Variable in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 13:18:16633browse

What Happens When You Assign a Negative Value to an Unsigned Variable in C  ?

Assigning Negative Values to Unsigned Variables: What Happens?

In C , if you attempt to assign a negative value to an unsigned variable, such as:

unsigned int nVal = 0;
nVal = -5;

the behavior can be perplexing.

The Explanation

According to Section 4.7 conv.integral of the C standard:

"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)."

In two's complement representation (which most modern processors use), this means there is no actual change in the bit pattern if there is no truncation. The result is the value that is equivalent to (-5 232), or 4294967291. This is because the two's complement representation of -5 is the same as the bitwise representation of 4294967291.

In short, assigning a negative value to an unsigned variable does not result in an overflow or exception. Instead, it wraps around to the equivalent positive unsigned value.

Note:

While this behavior is well-defined in C , it is not widely understood. It is important to be aware of this potential gotcha when working with unsigned variables.

The above is the detailed content of What Happens When You Assign a Negative Value to an Unsigned Variable in C ?. 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