0

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;
}
1
  • 1
    (iNumber / 2) becomes 2, which is then converted to a float, so the value will be 2. Order of operations. In the one before that, you cast iNumber to a float before it's divided, which is why it outputs 2.5. Commented Sep 27, 2016 at 20:15

2 Answers 2

2

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:

  1. Divide int iNumber by int 2 --> results in an int of 2
  2. Cast the result into a float --> results in a float of 2.

If 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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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++.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.