Thursday, April 9, 2009

How can %f work for type double in printf and %lf is required in scanf?

Answer: In variable-length argument lists such as printf's, the old "default argument promotions" apply, and type float is implicitly converted to double. So printf always receives doubles, and defines %f to be the sequence that works whether you had passed a float or a double.


(Strictly speaking, %lf is *not* a valid printf format specifier, although most versions of printf quietly excepts it.)

scanf, on the other hand, always accepts pointers, and the types pointer-to-float and pointer-to-double are very different (especially when you're using them for storing values). No implicit promotions apply.

No comments: