Domanda

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?

È stato utile?

Soluzione

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.)

Altri suggerimenti

The 2nd case is a C-style cast (as identified by bhuang3), but it's not the C-style equivalent to case 1. That would be b = (int)x;. And the C++ equivalent of case 2 would be b = *reinterpret_cast<int*>(&x); Either way you do it, case 2 is undefined behavior, because x occupies one byte, while forcibly reading an int's worth of data at x's address will either give you a segmentation fault (bus error on some systems) if it's not at a legal address for an int, or it will just read the next 3 bytes, whose values we don't know what they are. Thus it reads "garbage" as you observed.

  1. The static_cast doesn't provide runtime checks, which is used if you know that you refer to an object of a specific type.

  2. The seconde case actually is c-style cast

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top