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;
}
-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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.