tags:

views:

106

answers:

4

Hello! I'm not able to understand some typecasting syntaxes. For eg.

float f=7.0;
short s=*(short *)&f;

What's happening here short s=*(short *)&f? Looks like we're casting something as a pointer to a short and then initializing s to value stored in the address pointed to by something.

Now, this something looks like the address of variable f. So if something = address of f, it appears to me that we are making address of f as a pointer to some short and then de-referencing it. I know that what I've stated is wrong, but I just can't seem to visualize it.

Thanks.

+2  A: 

Your interpretation is correct. It's essentially forcing the compiler to treat the memory storing f as if it were actually treating a short. The result of this will be platform-dependent. This is very different to short s = (short)f;, which will just perform a nice conversion, and is well-defined.

Oli Charlesworth
+4  A: 

This syntax would make the most sense if short was the same size as float and even so, there would remain a problem with "strict aliasing rules".

It is used to interpret the bits of the float f as representing an integer. It is used to circumvent the fact that s = (short) f; would be interpreted as a conversion to integer. Truncation, I believe.

Pascal Cuoq
+1  A: 

1.whenever you type cast something ,it will must in the inside of brackets( ). 2.The inside of primitive types is not higher range (size) that of other primitive types(outside of brackets). 3.After type casting the variable it will be stored in the same primitive type of which you would convert. 4.Pointer means it stores the memory of address.it will indicate the star in c.(*)

AdalArasan
A: 

It shoud be:

float f=7.0; 
short s=*(short)&f; 

i.e the short is assigned a value 7

fahad