Reputation: 707
Working on casting between different datatypes in C++... The program here below prints:
>"Number is 2"
>"Number is 2.5"
>"Number is 2"
Please, explain why the last printout is not "Number is 2.5" which I would expect after the C++ style cast to float?
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
int iNumber = 5;
float fNumber;
// No casting - C++ implicitly converts the result into an int and saves into a float
// which is a conversion from 'int' to 'float' with possible loss of data
fNumber = iNumber / 2;
cout << "Number is " << fNumber << endl;
// C-style casting not recommended as not type safe
fNumber = (float) iNumber / 2;
cout << "Number is " << fNumber << endl;
// C++ style casting using datatype constructors to make the casting safe
fNumber = static_cast<float>(iNumber / 2);
cout << "Number is " << fNumber << endl;
_getch();
return 0;
}
Upvotes: 0
Views: 139
Reputation: 707
static_cast<float>(expression)
expects an expression in parentheses which parentheses will determine the order of the operations.
To effectively cast an int into a float without loss of data in the C++ style, the third expression needs to be rewritten with the parentheses around iNumber
alone as in fNumber = static_cast<float>(iNumber) / 2;
to eventually print "Number is 2.5
":
iNumber
is cast to float,2
is implicitly cast to 2.0
and iNumber
is divided by 2.0
.Notice that the parentheses defining the order of operations are around the datatype in C but around the variable in C++.
Upvotes: -1
Reputation: 636
The statement
fNumber = static_cast<float>(iNumber / 2);
is dividing an integer by an integer BEFORE the cast to a float. This results in the following steps:
int iNumber
by int 2
--> results in an int of 2If you instead do:
fNumber = static_cast<float>(iNumber / 2.0);
Now the result of the division will be a floating type of 2.5 before the cast and you should get 2.5 as expected.
Thats all well and good, but then why does
fNumber = (float) iNumber / 2;
work? This is because you're casting iNumber
to a float BEFORE the division operation, so here again, you're dividing a float by an int and the result will be a float of 2.5.
Upvotes: 2