float to int unexpected behaviour

前端 未结 6 835
情话喂你
情话喂你 2020-11-30 16:05

can you please explain the o/p behavior of this program.

int main()
{
  float a = 12.5;
  printf(\"%d\\n\", a);
  printf(\"%d\\n\", *(int *)&a);
  return         


        
6条回答
  •  忘掉有多难
    2020-11-30 16:33

    Casting a pointer and casting a value are very different operations. When you cast a float to an int, you ask to transform the float value to an int value, which results in actual transformation of data; when you cast a float pointer to an int pointer, you just override type checks. A pointer is just an integer memory location: casting it to another kind of pointer doesn't involve any transformation.

    So, what you see is what the bit pattern of your float looks like when treated as an integer.

    The bit patterns most computers use to represent floats are described by the IEEE-754 standard. Integers, on the other hand, are just, well, integers represented in binary base. Therefore, taking the bits of a real number and interpreting them as an integer yields very different results.

提交回复
热议问题