Sadek Sadek - 2 months ago 12
C Question

C printf difference between 0 flag & width attribute and precision flag

I'm currently learning the

function of libc and I don't understand, what is the difference between:

printf("Test : %010d", 10);

using the
flag and
as width specifier


printf("Test : %.10d", 10);

as precision specifier

That produce the same output:
Test : 0000000010


We'll start with the docs for printf() and I'll highlight their relevant bits.

First 0 padding.

`0' (zero)

Zero padding. For all conversions except n, the converted value is padded on the left with zeros rather than blanks. If a precision is given with a numeric conversion (d, i, o, u, i, x, and X), the 0 flag is ignored.

And then precision.

An optional precision, in the form of a period . followed by an optional digit string. If the digit string is omitted, the precision is taken as zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s conversions.

%010d says to zero-pad to a minimum width of 10 digits. No problem there.

%.10d", because you're using %d, says the minimum number of digits to appear is 10. So the same thing as zero padding. %.10f would behave more like you expected.

I would recommend you use %010d to zero pad. The %.10d form is a surprising feature that might confuse readers. I didn't know about it and I'm surprised it isn't simply ignored.