Zhe Chen
Zhe Chen

Reputation: 2957

Unsigned arithmetic in C++

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

Upvotes: 11

Views: 1726

Answers (1)

Bathsheba
Bathsheba

Reputation: 234705

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

Upvotes: 17

Related Questions