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