Scanf/Printf double variable C

Dragos Rizescu picture Dragos Rizescu · Nov 13, 2013 · Viewed 279.4k times · Source

Let's say I have this following bit of code in C:

double var;
scanf("%lf", &var);
printf("%lf", var);
printf("%f", var);

It reads from stdin variable 'var' and then prints twice in stdout 'var'. I understand that's how you read a double variable from stdin, but my questions are:

  1. Why can you print a double with %lf?
  2. Why can you print a double with %f?
  3. Which one is better and correct to use?

Answer

Yu Hao picture Yu Hao · Nov 13, 2013

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.