For the below expression:-
int main()
{
unsigned ui = 1;
float fval = 2.5;
cout << sizeof(ui) << endl << sizeof(fval) << endl;
cout << typeid(ui+fval).name();
}
we get the following output:-
4
4
f
It seems that ui+fval is a float.
However, given that both float and unsigned int are 4 bytes, and that not all of the unsigned int values can fit inside a float, shouldn't fval be converted to unsigned int?
The rules for arithmetic operators are actually slightly different than the rules for general function overload resolution.
From cppreference on arithmetic operators:
So, quite explicitly, when we're doing
unsigned + float, theunsignedgets converted to afloat. It's the first rule that applies, so we follow it.However, for general overload resolution, the conversion from
unsignedtofloatis equivalent to the conversion fromfloattounsigned. So for instance in the following code snippet:It's unable to decide which version of
addto use and fails to compile.