Dividing Different Data Types

Here, the denominator of the expression is type cast, ensuring the radius will be of type double. Does the denominator always determine the type of the result of a division expression? Why would the author not use a type coercion by instead writing 2.0 in place of static_cast<double>(2)?

 
radius = diameter / static_cast<double>(2);
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

template <typename T> const char* typeof(T&) { return "unknown"; }    // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(double&) { return "double"; }
template<> const char* typeof(float&) { return "float"; }

int main() {
    decltype(2.0/2) h1;
    std::cout << typeof(h1) << std::endl;
    
    decltype(2.0/2.0) h2;
    std::cout << typeof(h2) << std::endl;
    
    decltype(2.0/2.0f) h3;
    std::cout << typeof(h3) << std::endl;
    
    decltype(2.0f/2) h4;
    std::cout << typeof(h4) << std::endl;
    
    return 0;    
}


The denominator does not determine the type, but I believe the one requiring the most significant digits after the decimal point determines the type. As you can see if you run the above code, they are all coerced to type double except for the last one where it is now coerced to float
Last edited on
Topic archived. No new replies allowed.