c - Confusion regarding a printf statement -
so running code
#include<stdio.h> int add(int x, int y) { return printf("%*c%*c",x ,' ',y,' '); } int main() { printf("sum = %d", add(3,4)); return 0; }
and can't seem understand how following statement works
return printf("%*c%*c",x ,' ',y,' ');
so tried writing simple code
int x=3; printf("%*c",x);
and got weird special character (some spaces before it) output
printf("%*c",x,' ');
i getting no output. have no idea happening? please help. thank you.
this code
int x=3; printf("%*c",x,'a');
makes use of minimum character width can set each input parameter printf
.
what above print out a
character, specifies minimum width x
characters - output a
character preceded 2 spaces.
the *
specifier tells printf
width of part of output string formed input parameter x
characters minimum width x
must passed additional argument prior variable printed. width (if required) formed blank spaces output before variable printed. in case width 3 , output string (excluding quotes there illustrate spaces)
" a"
with code here
printf("%*c",x);
you have passed length value, forgotten pass variable want printed.
so code
return printf("%*c%*c",x ,' ',y,' ');
is saying print space character minimum width of x
characters (with code x = 3), print space character minimum of y
characters (in code y = 4).
the result printing out 7 blank space characters. length return value of printf
(and hence add
function) confirmed output of
sum = 7
from printf
inside main()
.
if change code
return printf("%*c%*c",x ,'a',y,'b');
you see string (obviously excluding quotes)
" b"
printed make happening more clear.
Comments
Post a Comment