0

When I compile and run the following snippet of code, the output is 0.000000.

#include <stdio.h>

int main(void)
{
    double a = 1.4;

    printf("%lf", a);

    return 0;
}

When I compile and run this snippet of code, the output is 1.400000, as I expected it to be for the first snippet.

#include <stdio.h>

int main(void)
{
    double a = 1.4;

    printf("%f", a);

    return 0;
}

Why is this the case? %lf is a format specifier for doubles so shouldn't the first snippet have the same output as the second?

Someone asked a similar question (Correct format specifier for double in printf) but according to the top answers, the two snippets should produce identical output as "the l is specified as having no effect if followed by the f conversion specifier (among others)" (quoted from first answer).

I'm using code-blocks as an IDE and I made the gcc compiler follow the 1999 standard for C. The possible duplicate says my code should work according to the C99 standard, which my compiler follows, but my code doesn't work. The answer in the duplicate therefore doesn't solve my problem.

1 Answers1

1

Quoting C11, chapter §7.21.6.1/ paragraph 7 (emphasis mine) [and chapter §7.19.6.1, C99, if you're interested]

The length modifiers and their meanings are:

[.....]

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.

If you compiler does not obey this, it's problem with the compiler conformance.

Your code is fine, both snippets are identical.

See live here

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • This helps me by telling me there's no problem with my code, but it doesn't solve my problem. I think it's something to do with code-blocks, because I did tick a box in settings to use the compiler conforming to the c99 standard. Your answer still applies to the C99 standard, right? –  Oct 26 '17 at 12:28
  • 1
    @programmer5934 absolutely. Chapter §7.19.6.1, C99, if you're interested. – Sourav Ghosh Oct 26 '17 at 12:29
  • 1
    @programmer5934 for completeness, the only standard **not** allowing the `l` here is the oldest one, C89/C90. –  Oct 26 '17 at 13:36