Why int plus uint returns uint?

前端 未结 3 1370
生来不讨喜
生来不讨喜 2020-12-20 13:14

int plus unsigned int returns an unsigned int. Should it be so?

Consider this code:

#include 
#include 

        
3条回答
  •  既然无缘
    2020-12-20 13:32

    If by "should it be" you mean "does my compiler behave according to the standard": yes.

    C++2003: Clause 5, paragraph 9:

    Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

    • blah
    • Otherwise, blah,
    • Otherise, blah, ...
    • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

    If by "should it be" you mean "would the world be a better place if it didn't": I'm not competent to answer that.

提交回复
热议问题