-3
cout<<-5u

It give output: 65531 why?

cout<<5u 

It just give output 5 Then why the outputs are different why -5u cant give -5 output.

kk_00
  • 11
  • 4
  • `u` is unsigned, so you just tried to print a negative number to a unsigned, this wrapped over to the maximum range for a unsigned int, 0-65531 – t0mm13b Apr 29 '17 at 11:40
  • Suppose that `unsigned` is 1 byte (for comodity; it's common to see them as 2 or 4 bytes). `5u` means `b00000101`, and because `-1u` is `b11111111` in binary, you just subtract 4 from it, so `-5u` is `b11111011`, which as an `int`, it is `251`. Scale this answer to the your `unsigned` size, and you'll get your answer. – Garmekain Apr 29 '17 at 11:51
  • The outputs are different because the values are different. – Pete Becker Apr 29 '17 at 12:44

1 Answers1

3

In C++ unsigned integers underflow and overflow in a well defined way (as apposed to signed integers). In particular, arithmetic operations are mod 2^n where n is the number of bits representing the unsigned int. -5u is equivalent to 0u - 5u which is equal to (0u - 1u) - 4u. 0u - 1u gives UINT_MAX(or std::numeric_limits<unsigned>::max()), which is 65535. So you have -5u = 65535 - 4 = 65531.

Daniel
  • 8,179
  • 6
  • 31
  • 56
  • 2
    To be pedantic: There is no overflow or underflow in unsigned integer arithmetic. Unsigned integers implement arithmetic in Z mod 2^NumBits and thus can represent any integer by choosing the representative of its equivalence class that lies in [0, 2^NumBits). – Baum mit Augen Apr 29 '17 at 11:52
  • Plzz tell me one thing how 0u-1u gives UINT_MAX – kk_00 Apr 29 '17 at 12:15
  • @user7919320 "arithmetic operations are `mod 2^n` where `n` is the number of bits representing the `unsigned int`". – Daniel Apr 29 '17 at 12:55
  • Daniel tell me how 0u-1u give. UINT_MAX – kk_00 Apr 29 '17 at 13:07
  • @user7919320 I have. Twice. – Daniel Apr 29 '17 at 13:20