0

My professor said that when you do scanf doubles are represented with %lf but in printf it's %f (which is for floats.) This is odd because he said that in his coding class we never use floats, only doubles. He didn't explain why.

I wrote a simple program that prints a double. I used printf with either %lf and %f. The result was the same.

What's the difference?

  • `printf` automatically promotes `float` to `double`: you cannot display a `float` with it. `l` has no uses with `f` (with `printf` a least) so it is most likely being ignored. – AugustinLopez Sep 30 '19 at 08:48

1 Answers1

3

For all "vararg" function (functions whose declarations contains ..., like for example printf and scanf) smaller types will be automatically promoted or converted to larger types. For example short will be promoted to int, and float will be promoted to double.

That means for printf the format %f and %lf are identical, since the argument will be a double.

But for scanf you don't pass values that will be promoted or converted, instead you pass pointers, for which no conversion will be made. And a pointer to float (i.e. float *) is very different from a pointer to double (i.e. double *). So for scanf there is a difference between %f and %lf.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621