What happens when I apply the unary operator "-" to an unsigned integer?

This should be a fairly simple question, but I cannot find the answer in my textbook and cannot find the right keywords to find it on the Internet.

What does this mean when you have a negative sign before an unsigned int?

In particular, if x is an unsigned int equal to 1, then what is the bit value of -x?

+5
source share
3 answers

In the C standard, arithmetic for unsigned integers is performed modulo 2 bits wide . So, for a 32-bit integer, negation will be taken modulo 2 32 = 4294967296.

For a 32-bit number, then the value you get if you cancel the number n will be 0-n = 4294967296-n . In your specific case, if unsigned int is 32 bits wide, you will get 4294967296-1 = 4294967295 = 0xffffffff (a number with all bits set).


The relevant text in standard C is given in ยง6.2.5 / 9:

a result that cannot be represented by the resulting unsigned integer type is reduced modulo by a number that is greater than the largest value that can be represented by the resulting type

+10
source

It will overflow in the negative direction, i.e. if your int is 16 bit x will be 65535 . The value of the bits will be 1111111111111111 (16 units)

If int is 32 bits, x will be 4294967295

+4
source

when you use "-", two integer additions are stored in a variable. see here for details

0
source

Source: https://habr.com/ru/post/1246845/


All Articles