Search code examples
c++visual-c++integer-overflowshort

short doesn't overflow visual c++ 2017


Input of 32760 and 9 print out 32769, not -32767.

I don't know what else to do, it's a simple program, but it doesn't work as I want.

#include <iostream>
using namespace std;

int main()
{
    short a, b;
    cin >> a;
    cin >> b;
    cout << a+b;
}

Solution

  • The result of the arithmetic operation a+b is not of type short. Instead the rules of integer promotion have it that the operands are first promoted to a larger integer type before addition.

    To make it "work" as you want, then something like this will force integer overflow (that you seem to want to see):

    short x = a + b;
    cout << x;