In K&R ANSI C book, section A.7.4.5 (Unary Minus Operator) it is stated:
… The negative of an unsigned quantity is computed by subtracting the promoted value from the largest value of the promoted type and adding one; …
How exactly is this calculated? Could you give a short C example?
I don’t see how this could yield the negative of, say, 200u: subtracting 200 from a max value of any integral type (signed or unsigned) and adding 1 does not result in -200.
I know what the Unary minus does – the problem is that I don’t see how the result is calculated according to the description.
Apparently you missed the word unsigned in the description you quoted. This is the key word in this case. In C language the “negative” of an unsigned quantity is still unsigned, meaning that it is not really negative. Unsigned values can’t ever be negative, by definition. They are always positive or 0. Arithmetic of unsigned values in C is modulo arithmetic or, in simple words, unsigned quantities “wrap around” when you perform arithmetical operations on them. Unary negation is not an exception. Calculating
-nwhennis unsigned is no different from calculating0 - n. Ifnisunsigned intand its value is200the expected result is not-200, but ratherUINT_MAX - 200 + 1, which is exactly what the quote is telling you.