int main(){ int i...">

Casting in (int *) of (& num) when num is a float in C

Why do I need the following code: "i is: 1075838976"?

#include <stdio.h> int main(){ int i = 2; float num = 2.5; i = *((int *)& num); printf("i is: %d\n", i); } 

Isn't that equivalent:

 #include <stdio.h> int main(){ int i = 2; float num = 2.5; i = num; printf("i is: %d\n", i); } 

What outputs: "i is 2"? Thanks.

+4
source share
3 answers

No, this is not at all equivalent.

It:

 i = num; 

converts a num value (which is 2.5 ) from float to int . The conversion truncates the value to 2 .

It:

 i = *((int *)& num); 

takes a pointer to a float num object, converts it to int* and splits the resulting pointer.

If you're lucky, it takes the bits that make up the num representation, pretends to be an int , and gives you these results.

If you're out of luck, then int and float may be of different sizes, the float object may not be aligned correctly for processing as an int object, or the result may even be a “trap representation” (although the latter is rare).

(I put the “lucky one” in quotes because, really, the best thing this code can do is to blow you in the face, which immediately allows you to understand that you are doing something dubious. The behavior is undefined, which means an error, but the implementation does not need to warn you about this at compile time or at run time.)

The specific value you get, 1075838976 , can be represented in hexadecimal as 0x40200000 . If you look at how float values ​​are represented on your system, you can probably figure out how this bit pattern ( 0100 0000 0010 0000 0000 0000 0000 0000 ) makes up the sign, mantissa, and exponent values ​​that represent 2.5 .

+11
source

In C, “cast” is kind of “overloaded” and does two completely different things:

- The reason code that must be generated to convert the "scalar" value between, say, int and float .

- force the pointer to another type. It actually does not generate any code and does not convert anything.

((int *)& num) enforces a pointer from float* to int* and does not perform any data conversion.

+3
source

You tell the machine to interpret the binary number explicitly as an int without going through the listing.

0
source

Source: https://habr.com/ru/post/1492991/


All Articles