Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the printf/snprintf format character %N do? (not %n)

Tags:

c++

Was going through some old code and found:

char buf[...];
int i = 1, j =2;
snprintf(buf, "%d-blah_%d-blah_%N", i, j);

Note only two passed vararg parameters, but 3 format strings.

It prints

1-blah_2-blah_0

Can't find this in any docs. What does %N do?

like image 480
marathon Avatar asked Feb 11 '23 12:02

marathon


2 Answers

According to standard documentation (e.g. POSIX printf) it does nothing defined (so %N could be undefined behavior, and is certainly unspecified behavior in the standards).

However, the GNU glibc offers customizing printf abilities. Your program might have registered (elsewhere) with register_printf_function something to handle %N. This is not standard and is GNU glibc specific (however, it is a convenient trick, but you can't teach GCC format function attribute to know about that trick.).

like image 90
Basile Starynkevitch Avatar answered Feb 14 '23 00:02

Basile Starynkevitch


It's an interesting case in Microsoft's CRT. What seems to happen is %N is treated as size specifier, but in the end it simply gets ignored.

You can find the source in <VSDIR>/VC/crt/src/output.c and for VS2013 you'll find following lines:

enum CHARTYPE {
    ...
    CH_SIZE,            /* 'h', 'l', 'L', 'N', 'F', 'w' */
    ...
};

'N' is also used in lookup state tables. The documentation says nothing about it, nor does it mention 'F'. Upon closer examination of the source code (case ST_SIZE) it turns out 'N', 'F' and 'L' (despite the docs!) are no-op size modifiers.

So, for VS2013 in your case you'd get 1-blah_2-blah_, without trailing 0.

like image 27
gwiazdorrr Avatar answered Feb 14 '23 01:02

gwiazdorrr