1

I'm aware that it can never be negative but what happens to the value in memory after it goes "below" 0?

example:

unsigned int i = 3;

while(i >=0){
    print("something");
    i=-i;
}
AS Mackay
  • 2,831
  • 9
  • 19
  • 25
  • https://stackoverflow.com/questions/8026694/c-unary-minus-operator-behavior-with-unsigned-operands – mnistic Dec 11 '18 at 02:24
  • You're flipping between `3` (i.e. `0x00000003`) and `-3` (i.e. `0xFFFFFFFD`). Because you're using `unsigned` the latter is _just_ a large _positive_ number. The actual bit pattern is the _same_ regardless of whether you've got `int` or `unsigned int`. It is how it is interpreted by the expression in the `while` that matters. This is "two's complement arithmetic": `-x --> ~x + 1`. That is, invert the bits, and then add 1. With a signed value, the most significant bit (e.g. `0x80000000`) if set means a negative number. – Craig Estey Dec 11 '18 at 02:25
  • 2
    Unsigned need not use 2's complement arithmetic; that is only the case if `UINT_MAX` is `2^n - 1` (but it need not be) ;) – Antti Haapala -- Слава Україні Dec 11 '18 at 02:27
  • 1
    @AnttiHaapala: That's all wrong. `UINT_MAX` (or any integer type's max) is required to be one less than a power of two. "Twos complement" is not relevant to unsigned types. They're just modular arithmetic mod a power of two. – R.. GitHub STOP HELPING ICE Dec 11 '18 at 04:51
  • Also the close-as-duplicate is wrong. The candidate duplicate https://stackoverflow.com/questions/2760502/question-about-c-behaviour-for-unsigned-integer-underflow is about assignment of a signed value to an unsigned object. This question is about a misunderstanding of unary `-` operator on unsigned operands. – R.. GitHub STOP HELPING ICE Dec 11 '18 at 04:54
  • @R.. yes `UINT_MAX` not `2^n - 1` is not conforming. As for the duplicate, you're correct... – Antti Haapala -- Слава Україні Dec 11 '18 at 05:00

1 Answers1

0

The unary - operator on an unsigned operand does not produce a value below zero. It produces a value which, when added to the operand in ordinary integer arithmetic, would yield one plus the maximal value the type can represent.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711