Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%.#s format specifier in printf statement in c

Please explain the output. What does %.#s in printf() mean?

#include<stdio.h>
#include <stdlib.h>

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

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

OUTPUT:

#s HE
like image 593
silentseeker Avatar asked Aug 30 '13 07:08

silentseeker


2 Answers

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 §7.21.6.1 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

like image 151
Yu Hao Avatar answered Sep 29 '22 20:09

Yu Hao


%.1s is used to print the first character of the string

%.2s is used to print the first two characters of the string

%.3s is used to print the first three characters of the string and so on

where # : alternative form of the conversion is performed is a flag which have an optional usage with the format parameter in printf() and fprintf() functions etc.

But as @Yu Hao said # is only used together with o, a, A, x, X, e, E, f, F, g, G, not including s.

in your case %.#s usage is Wrong.

Example usage from reference given by @WhozCraig :

printf("Hexadecimal:\t%x %x %X %#x\n", 5, 10, 10, 6);
printf("Octal:\t%o %#o %#o\n", 10, 10, 4);
like image 37
Gangadhar Avatar answered Sep 29 '22 20:09

Gangadhar