OK so I tried doing this
int b;
char x = 'a';
//Case 1
b = static_cast<int>(x);
std::cout<<"B is : "<<b<<std::endl;
//Case 2
b = *(int*)&x;
std::cout<<"B is changed as :: "<< b <<std::endl;
Now I know that in case 2, first byte of x is reinterpreted to think that it is an integer and the bit pattern is copied into b which gives of some garbage and in case 1 it just converts the value from char to int.
Apart from that are there any differences between these two?
The first one just converts the value:
int b = x;is the same asint b = static_cast<int>(x);.The second case pretends that there is an
intliving at the place where in actual fact thexlives, and then tries to read thatint. That’s outright undefined behaviour. (For example, anintmight occupy more space than achar, or it might be that thecharlives at an address where nointcan ever live.)