Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting, c language problem

Tags:

c

casting

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.

like image 771
Naruto Uzumaki Avatar asked Feb 27 '23 07:02

Naruto Uzumaki


2 Answers

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.

like image 64
Pascal Cuoq Avatar answered Mar 06 '23 18:03

Pascal Cuoq


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.

like image 34
Oliver Charlesworth Avatar answered Mar 06 '23 18:03

Oliver Charlesworth