Zhe Chen
Zhe Chen

Reputation: 2967

Addition between `signed int` and `unsigned int`

Here is an example from "C++ Primer" which indicates that signed int will be automatically converted to unsigned int when added with unsigned int. But the result I got seemed to be that unsigned int was casted to signed int instead. Could anyone tell me why?

Code:

#include <iostream>

using namespace std;

int main() {
    int i = -1;
    unsigned int u = 10;

    cout << i + u << endl;

    return 0;
}

Result:

9

Upvotes: 0

Views: 76

Answers (1)

Barry
Barry

Reputation: 303880

That's a pretty uninteresting example. How can you tell if 9 is a signed or unsigned int (or long or short or ...)? It's in the range of all of these types.

Here's a better example:

int i = -12;
unsigned int u = 10;
cout << i + u << endl; // prints 4294967294

Or really:

static_assert(is_same<decltype(i+u), unsigned int>::value,
              "wat");

Upvotes: 4

Related Questions