What's the use of suffix `f` on float value

前端 未结 7 601
失恋的感觉
失恋的感觉 2020-11-28 04:25

I am wondering what the difference is between these two variables in C:

float price = 3.00;

and

float price = 3.00f;
         


        
7条回答
  •  庸人自扰
    2020-11-28 05:26

    In addition to what has already been said, keeping track of 1.0 versus 1.0f is more important than many people realize. If you write code like this:

    float x;
    ...
    float y = x * 2.0;
    

    Then x will be promoted to a double, because 2.0 is a double. The compiler is not allowed to optimize that promotion away or it would violate the C standard. The calculation takes place with double precision, and then the result is then implicitly truncated into a float. This means that the calculation will be slower (though more accurate) than it would have been if you had written 2.0f or 2.

    Had you written 2, the constant would be of int type, which would be promoted to a float, and the calculation would have been done with "float precision". A good compiler would warn you about this promotion.

    Read more about the "usual arithmetic conversion" rules here:

    http://msdn.microsoft.com/en-us/library/3t4w2bkb%28v=vs.80%29.aspx

提交回复
热议问题