0
#include <iostream>
int main()
{
    unsigned int x{ 2 };
    int y{-3};
    std::cout<<x+y;

    return 0;
}

This code is giving me the answer 4294967295.

#include <iostream>
int main()
{
    unsigned short x{ 2 };
    short y{-3};
    std::cout<<x+y;

    return 0;
}

When I change the int in previous code to short the new answer is -1.

As per my knowledge the correct answer in both cases should be 4294967295, This is because signed and unsigned integers arithmetic produce unsigned result but while using the short keyword the answer I get is different. But I don't understand why the code using short is giving the wrong answer, Can anyone explain what is going wrong here?

EDIT: This is NOT a duplicate of the other question. Stop flagging this ! Someone please unflag this

I have read What happens when I mix signed and unsigned types in C++? and it's helpful, but it doesn't address my question.

I am reposting this question because when I first asked this question someone flagged the question saying that it was duplicate but it was not so please dont flag this question

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
mr_nobody
  • 23
  • 5
  • 1
    Try cppinsights to get explanation: https://cppinsights.io/s/7581a6d7 https://cppinsights.io/s/8bef8491 @AhmedAEK you are wrong. Conversion form singed to unsigned is well defined even in case of overflow. – Marek R Jul 12 '23 at 11:49
  • I never told conversion from signed to unsigned is not well defined, my problem is that the same piece of code produces different output while using int and short – mr_nobody Jul 12 '23 at 12:00
  • @mr_nobady I was referring to deleted comment done to by other user. – Marek R Jul 12 '23 at 12:01
  • oh sorry my mistake! – mr_nobody Jul 12 '23 at 12:03
  • You asked the same question yesterday where it had already been answered – chrysante Jul 12 '23 at 12:07
  • @chrysante I asked the same question yesterday and it was not answered instead someone flagged this question as duplicate and I dont know why – mr_nobody Jul 12 '23 at 12:09

1 Answers1

4

In the example with int, the calculation is converted to unsigned int. With short, it is converted to (signed) int.

This is because:

https://en.cppreference.com/w/c/language/conversion

Integer promotions

Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int ....

If int can represent the entire range of values of the original type (or the range of values of the original bit-field), the value is converted to type int. Otherwise the value is converted to unsigned int.

Integer promotions preserve the value, including the sign: ...

Martin Ba
  • 37,187
  • 33
  • 183
  • 337