3

code one is:

int a = 0x42500000;
float *f = (float *)&a;    
printf("%f", *f);     //output 52.00000

code two is:

int a = 0x42500000;
float f = (float)a;    
printf("%f", f);        //output 0.00000

why code two output 0.00000,who can tell me why?

artwl
  • 3,502
  • 6
  • 38
  • 53
  • 2
    Side Note: Your first example is technically undefined behavior because it violates [Strict Aliasing](http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule). – Mysticial Feb 17 '12 at 09:40
  • 1
    @Mysticial: not only is it technically undefined behavior, I've seen simple examples along these lines actually fail in practice on GCC with lots of optimization. The compiler determines that the value of `a` is never (validly) used, and doesn't bother initializing it. Even if you do use the value of `a`, it can reorder the initialization *after* the use of `*f`. – Steve Jessop Feb 17 '12 at 09:57

2 Answers2

4

First snippet interprets the contents of the memory location of a as if it were float, without casting. Unless you really know what you are doing, you don't want to do that, it's almost always a mistake.

The second snippet casts the value of a to float, which should give you the same value as the int. It really does do that. Your code gives me 1112539136.000000. What compiler are you using and getting 0 there?

Irfy
  • 9,323
  • 1
  • 45
  • 67
2

The first cast tells the compiler to assume that the location where a is stored is a float and consider it likewise.
The second tells the compiler to assume that a is a float and consider it likewise.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 4
    "The second tells the compiler to assume that a is a float" - no it doesn't, it tells the compiler to convert the value of `a` to a float value (the nearest, which for this example is exact since it requires only 11 bits of precision). `a` remains an int and is never treated as any other type. – Steve Jessop Feb 17 '12 at 09:46