0

Can anyone explain what lines 5 & 7 mean?

int a;
double b = 2.3;
a = b;
cout << a << endl;
a = int(b); // <-- here
cout << a << endl;
a = (int)b; // <-- here
cout << a << endl;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    They are styles (1) and (2) here of [explicit type conversion](https://en.cppreference.com/w/cpp/language/explicit_cast). They are equivalent, and consist of several possible conversions attempted in succession. In this case the `static_cast` is what actually converts from double to int. – Nathan Pierson Sep 21 '21 at 19:56
  • @Shadman Ehsan They mean the same as a = b;.:) – Vlad from Moscow Sep 21 '21 at 19:56
  • 1
    Line 5: `a=int(b);` This cast the variable `b` to an integer and stores the result in `a`. Since `b` happens to be a `double`, the result will be floored. Line 7: `a=(int)b` This is known as an explicit "C-Style" cast. It has the same effect of Line 5 but there are no guarantees that the result is valid (in this case it will be fine, but you can't just cast *any* type to another and expect it to work as intended unless type conversions are defined for those types). – h0r53 Sep 21 '21 at 19:56
  • You seem to have it, in that you know the term cast. The lines employ a C-style cast of the double b, to an int. – sweenish Sep 21 '21 at 19:56
  • @h0r53 -- to be clear, there is no guarantee that any of the three conversions (lines 3, 5, and 7) from double to int will be valid, although with the value assigned in line 2, all three will be okay. The form of the conversion doesn't matter. – Pete Becker Sep 21 '21 at 19:59
  • 5) functional cast expression 7) C-style cast expression. – Ted Lyngmo Sep 21 '21 at 19:59
  • This should be of use: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – eerorika Sep 21 '21 at 20:03
  • But... But... But... That requires READING! – user4581301 Sep 21 '21 at 20:12

1 Answers1

0

This is called C-style casting and is not recommended to be used in c++ because it can bring to precision loss. What happens here is that the double type is represented in memory as a structure holding the whole part and the floating part. And when you say a = int(someVariableNameWhichIsActuallyDouble) it takes only the whole part of that variable and assigns it to a. So for example if you have b = 2.9; and you want to take only the whole part of the number you can do a c-style cast. But since you wrote C++ type casting for such cases i recommend you to use a = static_cast(b); But be cautious because when doing narrowing casting(casting from a larger type to a narrower type) you need to be causios not to loose precision.