-5

If I do this assignment

float x = 16.8;
unsigned int i = *(unsigned int*) &x;

What will be the value of the variable i? What it is the logic of this assignment?

alpereira7
  • 1,522
  • 3
  • 17
  • 30
cheroky
  • 755
  • 1
  • 8
  • 16

1 Answers1

1

With a code like this, you could have seen the answer in your precise case:

#include <stdio.h>

int main(void)
{    
    float x = 1;
    unsigned int i = *(unsigned int*) &x;
    printf("%d\n", i);

    return 0;
}

This type of assignment is illegal, by casting a pointer to a float into a pointer to an unsigned int, then dereferencing it, you are against the Strict Aliasing Rule.

As it was said in the comments, there is no strict answer. Even if with a rounded x like :

float x = 16;

You will probably not have an expected i = 16.

In most cases, your code will seem correct, you will not be warned or anything, and you code will run. So be careful!

alpereira7
  • 1,522
  • 3
  • 17
  • 30