Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why int plus uint returns uint?

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

Consider this code:

#include <boost/static_assert.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/type_traits/is_same.hpp>

class test
{
    static const int          si = 0;
    static const unsigned int ui = 0;

    typedef BOOST_TYPEOF(si + ui) type;
    BOOST_STATIC_ASSERT( ( boost::is_same<type, int>::value ) ); // fails
};


int main()
{
    return 0;
}
like image 972
Vahagn Avatar asked Apr 06 '12 18:04

Vahagn


1 Answers

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.

like image 63
Robᵩ Avatar answered Oct 20 '22 00:10

Robᵩ