num = 1.23456;
That sets the value of num
to 1. (The fractional part, .23456, is discarded, since according to the C language rules, an int can't hold fractional values)
*((float*) &num) = 1.23456;
Here you are taking the floating-point value 1.23456 and overwriting the memory location where num
lives with that bit-pattern. I suspect that this is invoking undefined behavior; in any case this can only 'work' on computers where sizeof(float)==sizeof(int), so it's a bad idea to do this.
printf("num = %.2f \n", *((float*)&num));
Here you are pretending that the memory location where num
is located is actually the location of a float, and printing out that memory as if it were a floating point value. It just so happens to do what you expected, on your machine, but you shouldn't rely on it doing so. By doing tricky casting and type-punning like this, you are effectively "going behind the compiler's back" and bypassing its type-system. The likely way this will bite you (even on computers where float and int both take up the same number of bytes) is when you enable optimizations and the compiler optimizes your code in some way that assumes that an int and a float can't occupy the same address in memory -- but your code is deliberately breaking that assumption, and thus your program ends up doing something unexpected (like crashing, or printing out the wrong value).
Is the following type cast creates a new variable in memory?
C being a fairly low-level language (by modern standards anyway), it is trying to do what your program told it to do, no more and no less. In particular, your program told it to treat a pointer-to-int as a pointer-to-float, and the C compiler trusts that you know what you are doing and lets your violate the type system by using casts. So the program isn't creating a new variable in memory so much as overwriting the bytes of memory where an existing variable (num
) is located, in a questionable and unsafe way.