What is the point of using 'f' when assigning a value to a CGFloat?

前端 未结 2 1698
情书的邮戳
情书的邮戳 2021-02-07 11:52

I see this all the time:

CGFloat someCGFloat = 1.2f;

Why is the \'f\' used? If the CGFloat is defined as float, the v

2条回答
  •  一整个雨季
    2021-02-07 11:52

    In your snippet, just an assignment, you don't need the 'f' suffix, and in fact you shouldn't use it. If CGFloat is single precision (like in iOS) then your value will be stored single precision with or without the 'f' and if CGFloat is double precision (like on Mac OS) then you'll be unnecessarily creating a single precision value to be stored double precision.

    On the other hand, if you're doing arithmetic you should be careful to use 'f' or not use it as appropriate. If you're working with single precision and include a literal like '1.2' without the 'f' then the compiler will promote the other operands to double precision. And if you're working with double precision and you include the 'f' then (like the assignment on Mac OS) you'll be creating a single precision value only to have it immediately converted to double.

提交回复
热议问题