We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.
For scanf , %f reads into a float , and %lf reads into a double . For printf : In C99 and later, they both are identical, and they print either a float or a double . In C89, %lf caused undefined behaviour although it was a common extension to treat it as %f .
For printf, arguments of type float are promoted to double so both %f and %lf are used for double. For scanf, you should use %f for float and %lf for double.
To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.
Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.
Since С99 the matching between format specifiers and floating-point argument types in C is consistent between printf and scanf. It is
%f for float
%lf for double
%Lf for long double
It just so happens that when arguments of type float are passed as variadic parameters, such arguments are implicitly converted to type double. This is the reason why in printf format specifiers %f and %lf are equivalent and interchangeable. In printf you can "cross-use" %lf with float or %f with double.
But there's no reason to actually do it in practice. Don't use %f to printf arguments of type double. It is a widespread habit born back in C89/90 times, but it is a bad habit. Use %lf in printf for double and keep %f reserved for float arguments.
scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.
Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With