What happens if I assign a negative value to an unsigned variable?

前端 未结 6 973
旧巷少年郎
旧巷少年郎 2020-11-22 07:31

I was curious to know what would happen if I assign a negative value to an unsigned variable.

The code will look somewhat like this.

unsigned int nVa         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:10

    For the official answer - Section 4.7 conv.integral

    "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). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

    This essentially means that if the underlying architecture stores in a method that is not Two's Complement (like Signed Magnitude, or One's Complement), that the conversion to unsigned must behave as if it was Two's Complement.

提交回复
热议问题