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

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

Linda Hamilton
Release: 2024-12-16 20:54:12
Original
963 people have browsed it

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

Assigning Negative Values to Unsigned Variables: Uncovering the Mystery

Intrigued by the potential outcome of assigning negative values to unsigned variables, a programmer embarked on an experiment. Assigning a negative value of -5 to an unsigned integer variable named nVal, they were surprised by the compiler's lack of errors. However, running the program revealed an unexpected result - nVal held a peculiar value.

Seeking an explanation, the programmer delved into the C standard. Section 4.7 conv.integral regarding the conversion from signed integer types provided insights. According to the 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 essence, this means that for non-Two's Complement architectures (e.g., Signed Magnitude, One's Complement), the conversion to unsigned behaves as if Two's Complement were used. Furthermore, adding or subtracting 2n repeatedly until the value falls within the unsigned type's range is mathematically equivalent to 2's complement sign-extension or truncation.

Specifically, for 2's complement, the bit pattern remains unchanged because adding 2n cancels out any changes: the low n bits of 2n are all zeros. This property makes 2's complement addition/subtraction equivalent to unsigned operations bitwise, hence its special status.

It's noteworthy that conversion from floating point to unsigned integers differs. In such cases, negative values or those exceeding the unsigned type's range result in undefined behavior. Only signed integer to unsigned integer conversions employ modulo reduction.

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