In python, type casting is done as:
float(a)
if the variable a
is, say an integer and needs to be converted to float.
Now consider the following C++ code:
int a=5;
int b=10;
cout<< (float) a/b<<endl;
cout<<static_cast<float> (a/b)<<endl;
cout<<static_cast<float> (a)/b;
which gives the output:
0.5
0
0.5
In the first type cast, a
is type casted to float explicitly, and then b
is type casted implicitly. The final answer is of the type float
.
In the second and third type cast, depending on the position of the ()
either a
is first explicitly converted to float, then b
implicitly converted and then then the final value is 0.5 or a/b
is first calculated as an int, and then type casted to float, making the final value 0.
There is no ambiguity while using static_cast<type>(expr)
My question being:
Wouldn't this be a lot clearer if the first line was written like:
cout<<float(a)/b<<endl;
Eliminating any ambiguity regarding in which order the type casting will be done?
C++ has no restrictions on doing just that, and yet it isn't common practice. Rather, cout<<(int)a/b<<endl;
is the prevelant form, which seems to be more ambiguous.
Why is this the case?
Another way to frame this question would be: what advantage does the (type) expression
offer over type (expression)
?