c - Why printf is not able to handle flags, field width and precisions properly? -


i'm trying discover capabilities of printf , have tried :

printf("test:%+*0d", 10, 20); 

that prints

test:%+100d

i have use first flag +, width * , re-use flag 0.

why it's make output ? purposely used printf() in bad way wonder why shows me number 100?

this because, you're supplying syntactical nonsense compiler, free whatever wants. related reading, undefined behavior.

compile code warnings enabled , tell like

warning: unknown conversion type character ‘0’ in format [-wformat=]
printf("test:%+*0d", 10, 20);
^

to correct, statement should either of

  • printf("test:%+*.0d", 10, 20); // note '.'

    where, 0 used precision

    related, quoting c11, chapter §7.21.6.1, (emphasis mine)

    an optional precision gives minimum number of digits appear d, i, o, u, x, , x conversions, number of digits appear after decimal-point character a, a, e, e, f, , f conversions, maximum number of significant digits g , g conversions, or maximum number of bytes written s conversions. the precision takes form of period (.) followed either asterisk * (described later) or optional decimal integer; if period specified, precision taken zero. if precision appears other conversion specifier, behavior undefined.

  • printf("test:%+0*d", 10, 20);

    where, 0 used flag. per syntax, all flags should appear together, before other conversion specification entry, cannot put anywhere in conversion specification , expect compiler follow intention.

    again, quote, (and emphasis)

    each conversion specification introduced character %. after %, the following appear in sequence:

    • zero or more flags (in order) [...]
    • an optional minimum field width [...]
    • an optional precision [...]
    • an optional length modifier [...]
    • a conversion specifier [....]

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -