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.
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.
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
.