I just observed a strange phenomenon when doing unsigned arithmetic. It's expected that b
and -a
have the same number 4294967286
due to wraparound, but the actual output for b
and -a
is -10
and 4294967286
respectively. Could anyone help give a hint?
#include <iostream>
int main() {
unsigned int a = 10;
int b = -a;
std::cout << b << ", " << -a << std::endl;
}
https://repl.it/repls/ExpertDrabOrganization
-a
is evaluated in unsigned
arithmetic, and will be a number larger than std::numeric_limits<int>::max()
. The unary operator -
when applied to an unsigned
type acts more like a modulus operator.
Therefore the behaviour of your program is implementation defined due to an out-of-range assignment to an int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With