Search code examples
32bit-64bitieee-754cgfloat

Is it safe to set a CGFloat to a double?


I have the following code running on a 64-bit device:

CGFloat myFloat = 123.45f;
CGFloat myDouble = 123.45;

Is this safe across 32- and 64-bit devices? Since CGFloat changes sizes based on the processor architecture, will the given variables contain values close to 123.45 on both platforms, or will something make them blow up due to bits being placed incorrectly?

Can one of these two things happen?

In 64-bit:

myFloat  == 0x0000000042F6E666 == 5.5507143600000000e-315
myDouble == 0x405EDCCCCCCCCCCD == 123.45

In 32-bit:

myFloat  == 0x42F6E666 == 123.45
myDouble == 0xCCCCCCCD == -1.0737418e8

Now, I haven't seen this in the field yet... which spawns my other question: Why haven't I seen this problem in the field?


Solution

  • Remember that your code is compiled twice, once for 32-bit and once for 64-bit.

    When compiling for 32-bit, your code looks like this:

    float myDouble = 123.45;
    

    So, the answer to your question is yes, the compiler knows how to handle that code and it will work just fine.

    What you do need to watch for is the loss of precision when a 64-bit double value is assigned to a 32-bit float variable. In that case, the compiler will generate a warning for you about the loss of precision, but you will only see the warning when compiling the 32-bit version of your code.