silentseeker silentseeker - 1 year ago 122
C Question

%.#s format specifier in printf statement in c

Please explain the output. What does


#include <stdlib.h>

int main(int argc,char*argv[]){

char *A="HELLO";
printf("%.#s %.2s\n",A,A);
return 0;


#s HE

Answer Source

It's undefined behavior. # in printf format specifier means alternative form, but according to the standard, # is only used together with o, a, A, x, X, e, E, f, F, g, G, not including s.

C11 § The fprintf function Section 6

# The result is converted to an ‘‘alternative form’’. For o conversion, it increases the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point character, even if no digits follow it. (Normally, a decimal-point character appears in the result of these conversions only if a digit follows it.) For g and G conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.

For example, on my machine, output is different: %.0#s HE