Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned arithmetic in C++

Tags:

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

like image 727
Zhe Chen Avatar asked Nov 20 '18 08:11

Zhe Chen


Video Answer


1 Answers

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

like image 133
Bathsheba Avatar answered Oct 16 '22 15:10

Bathsheba