I have been having some problems with downward type conversion in C++ using pointers, and before I came up with the idea of doing it this way Google basically told me this is impossible and it wasn’t covered in any books I learned C++ from. I figured this would work…
long int TheLong=723330;
int TheInt1=0;
int TheInt2=0;
long int * pTheLong1 = &TheLong;
long int * pTheLong2 = &TheLong + 0x4;
TheInt1 = *pTheLong1;
TheInt2 = *pTheLong2;
cout << "The double is " << TheLong << " which is "
<< TheInt1 << " * " << TheInt2 << "\n";
The increment on line five might not be correct but the output has me worried that my C compiler I am using gcc 3.4.2 is automatically turning TheInt1 into a long int or something. The output looks like this…
The double is 723330 which is 723330 * 4067360
The output from TheInt1 is impossibly high, and the output from TheInt2 is absent.
I have three questions…
Am I even on the right track?
What is the proper increment for line five?
Why the hell is TheInt1/TheInt2 allowing such a large value?
This invokes undefined behavior, because the C++ Standard does not give any guarantee as to which memory location
pTheLong2is pointing to, as it’s initlialized as:&TheLongis a memory location of the variableTheLongandpTheLong2is initialized to a memory location which is either not a part of the program hence illegal, or its pointing to a memory location within the program itself, though you don’t know where exactly, neither the C++ Standard gives any guarantee where it’s pointing to.Hence, dereferencing such a pointer invokes undefined behavior.