What is the diference between static_cast<int>(var) and *(int*)&var?
c++, static-cast, type-conversion
Solution
The first one just converts the value: `int b = x;` is the same as `int b = static_cast<int>(x);`.
The second case pretends that there is an `int` living at the place where in actual fact the `x` lives, and then tries to read that `int`. That's outright undefined behaviour. (For example, an `int` might occupy more space than a `char`, or it might be that the `char` lives at an address where no `int` can ever live.)
Problem
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?