Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are %f and %lf interchangeable when using printf? [duplicate]

In an article on the w3resource.com, I've seen the following code:

double x, y;
pr1 = sqrt(pr1);
x = (-b + pr1)/(2*a);
y = (-b - pr1)/(2*a);
printf("Root1 = %.5lf\n", x);
printf("Root1 = %.5lf\n", y);

The article says to take three floating-point numbers. But in their solution (this code snippet), they have used the %lf format specifier. Why have they used %lf instead of %f? Can I also use %f instead of %lf for floating-point numbers?

If I use a float keyword instead of double, and use %f, is there any issue? The output is the same for me.

like image 763
Anik Sen Avatar asked Feb 03 '26 04:02

Anik Sen


1 Answers

%f has different meaning in printf and scanf family functions:

  • in printf, %f and %lf are equivalent, and both are matched by double. This is because in variadic functions, all float arguments are promoted to double when the function is called, so there is no difference between passing float and double at a language level.
  • in scanf, %f matches a float* and %lf matches a double*, and this distinction is very important. Using the wrong type of pointer will result in undefined behavior.

You can also use cdecl+ to better understand printf and scanf calls. The output is as follows:

printf("Root1 = %.5lf\n", x)
Write "Root1 = "
Write a decimal double with lower-case infinity/NaN symbols
    precision: 5
Write "\n"

ARGUMENTS & EXPECTED TYPES
--------------------------
x (double)

When in doubt, use %f for float and %lf for double, even in printf, where there is no difference between the two. You will introduce pointless inconsistencies between your scanf and printf format strings otherwise.

Note on floating-point numbers

You may have gotten confused by the meaning of float and floating-point number. float, double, long double, and more are floating-point numbers in C. When the article says floating-point number, they could also mean double, _Decimal32, _Float128, etc.

Why doesn't scanf promote float* to double* similar to printf?

This is not possible, because the object in which we're storing the float cannot be used to store a double.

  • At a language level, this would be a strict aliasing violation.
  • At an implementation-level, we would try to store e.g. eight bytes of double in a float which consists of four bytes, which is impossible.
like image 145
Jan Schultke Avatar answered Feb 05 '26 20:02

Jan Schultke