Why does scanf() need “%lf” for doubles, when printf() is okay with just “%f”?

后端 未结 5 2039
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:03

Why is it that scanf() needs the l in \"%lf\" when reading a double, when printf() can use \"%f

5条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 06:54

    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.

提交回复
热议问题