Sadek - 27 days ago 6

C Question

I'm currently learning the

`printf`

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

using the

`0`

`10`

and

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

using

`10`

That produce the same output:

`Test : 0000000010`

Answer

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

First 0 padding.

`0' (zero)

Zero padding.

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

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.

, 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.This gives the minimum number of digits to appear for d, i, o, u, x, and X 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.