I wrote the piece of code below just now with reinterpret_cast and then staic_cast(writing the same code for both) to try evaluate my understanding of the two and they both returned the same result which is not what I was expecting.
I guess my initial understanding before writing this was wrong, as I thought static_cast would give me a different return value to reinterpret_cast.
The result is 'e' to be precise about it. Which is the character literal for the binary value 101?
Is there someone who understands what my code is doing, that is willing to explain it, please?
1 2 3 4 5 6 7 8 9 10
#include <iostream>
usingnamespace std;
int main()
{
int x=101;
int *xptr = &x;
char y = reinterpret_cast<int>(*xptr);
cout << y << endl;
return 0;
}
10287228? What value has been placed into 'i'? As they are both an int type, is it the memory value of arr[5] how it would be represented as a single interger
An array stores the elements in contiguous memory blocks. The compiler treats each blocks as a separate entity.
reinterpret_cast forces the compiler to see the 5 separate blocks as one block five times bigger.
I missed it the first time, your use of reinterpret_cast is logically flawed. You thought you were casting int to char. You actually cast int to int. The compiler can do an implicit cast from int to char itself.
Line 7 is the equivalent of char y = (*xptr);.
char y = reinterpret_cast<char>(*xptr); is an invalid cast. char y = reinterpret_cast<char>(xptr); is a valid cast, if imprecise due to bit truncation.
* retyping references
* retyping pointers
* obtaining an address out of a pointer (or building a pointer from an address)
* same-type conversion (which does nothing)
1 2 3
int x=101;
int *xptr = &x;
char y = reinterpret_cast<int>(*xptr);
here *xptr is an int, the cast to int is a same-type conversion that does nothing. This is equivalent to char y = 101;