You lose precision, it's fairly self explanatory.
In this case there's 2 reasons why you do.
- An integer only has 4 bytes, whereas a double has 8, meaning you can't put the entire double into the integer. (In reality it's implementation defined)
- A double has decimal numbers, an integer does not, so an integer simply cannot hold information about decimal numbers.
The reason that line errors is because you're trying to cast a pointer to an integer, which is not possible, what you meant to do is j = (int)*p;
There's several bad practices in your code.
- using namespace std;
Why is "using namespace std;" considered bad practice?
https://isocpp.org/wiki/faq/coding-standards#using-namespace-std
How to use an iterator? (example of it causing problems)
Confusion about pointers and references in C++ (another example of it causing problems; using std::swap; would cause the same exact problem as well)
- C style casts
This is
(type)
, in your case specifically (int)
There are 2 main casts that should be used in C++, static_cast and reinterpret_cast.
(There are 2 more types, const_cast and dynamic_cast, but these are irrelevant in this case, and const_cast should almost never be used)
Both take a template parameter to the resulting type.
In this case, you could probably i = static_cast<int>(d);
For the second cast, j =, you should (in reality you shouldn't cast pointers to different types)
j = *reinterpret_cast<int*>(p);
Of course, casting doubles to integers isn't considered good, but this should fix your compiler error.