Float + int = ??

Where can I find informations regarding addition/subtraction/multiplcation/division of float/int/double numbers?
According to the code below, I ended up getting 2int and 7float, which output 9.
So, does int + float = float ?
one thing I know is if you have a double, double will be always the output number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   #include <iostream>
    using namespace std;
    float doit(int a, int b)
    {
            return a * b;
    }
    float doit(float a, float b)
    {
            return a + b;
    }
    int main()
    {
            cout << doit(doit(1,3),doit(3.f,4.f));
            return 0;
    }  
Last edited on
Where can I find informations regarding addition/subtraction/multiplcation/division of float/int/double numbers?

there is a summary at http://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions

does int + float = float ?

yes; to quote the link, "if either operand is float, the other operand is converted to float" (so the int 2 becomes the float 2.0), and the return type is the same as the result of that conversion (also float)
for clarity it's often a good idea to explicitly cast. In visual studio, you get truncation warnings if you cast in a specific direction implicitly (such as double to float, or unsigned int to signed int). By explicitly casting, you are acknowledging the cast and you are aware of the truncation risk. It also helps to remove any ambiguity that others might read in your code.

Topic archived. No new replies allowed.