Wednesday 2 October 2019

c - Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?



Why is it that scanf() needs the l in "%lf" when reading a double, when printf() can use "%f" regardless of whether its argument is a double or a float?



Example code:




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

Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...