0

I know that similar questions are already posted many times here and I searched with Google and here and read answers to those questions, but there is something not clear to me and here it is:

float x = 1.5; 
float z = 0.0;
z = x + 5.22f;

Here I am convinced that it is necessary to add f after the number 5.22 so that the compiler won't treat it as double.

The point is in the book I am reading the author do this:

float myvar = 2.55f;

My question is: I already declared "myvar" to be float what is the purpose of the f suffix? Why the repetition?

Is it possible that the compiler treats the value 2.55 as a double and when it tries to assign it to myvar it demotes it to float, so the purpose of the f is to prevent this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • I don't think it is necessary. The author may be being overly prudent. – Jiminion May 11 '14 at 16:02
  • 1
    @shree.pat18 , thank you , i didn't get this post when i searched . it has the answer to my question , thank you – myNameIsBahaa May 11 '14 at 16:05
  • @Jim , thank you for replaying , i found this in the "@see.pat18" link , it says : float x = 0.0 has an implicit typecast from double to float. Depending on the compiler, implicit typecast can require the compiler to generate extra code. – myNameIsBahaa May 11 '14 at 16:08
  • 1
    Your compiler may emit a warning for assigning a double to a float. The f suffix forces the constant to be a float, thereby avoiding the warning. – Raymond Chen May 11 '14 at 16:11
  • @RaymondChen, thank you sir , i will check the warning lever in my compiler ,thank you very much – myNameIsBahaa May 11 '14 at 16:21

1 Answers1

4

Unadorned floating point constants are double values. Therefore, in:

float x = 1.5;

the 1.5 is a double value. Now, in this context, even the most dim-witted compiler is going to generate the same code as it would if you wrote:

float x = 1.5f;

So in this context, it doesn't matter. When does it matter? When you use the constant in a calculation:

float y = x * 2.3;

The multiplication is done using double and then the result converted to float, compared with:

float z = x * 2.3f;

where the multiplication is done using float. In pre-standard C, all floating point computations were done in double, so the distinction didn't matter, but all versions of Standard C allow the computation for all operands float to be done in float.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278