简体   繁体   中英

Confusion regarding a printf statement

So I was running this 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 to understand how does the following statement works

return printf("%*c%*c",x ,' ',y,' ');  

So I tried writing a simple code

int x=3;
printf("%*c",x);

and I got a weird special character (some spaces before it) as output

printf("%*c",x,' ');

I am getting no output. I have no idea what is happening? Please Help. Thank you.

This code

int x=3;
printf("%*c",x,'a');

makes use of the minimum character width that can be set for each input parameter to printf .

What the above does is print out the a character, but specifies that the minimum width will be x characters - so the output will be the a character preceded by 2 spaces.

The * specifier tells printf that the width of the part of the output string formed from this input parameter will be x characters minimum width where x must be passed as additional argument prior to the variable that is to be printed. The extra width (if required) is formed from blank spaces output before the variable to be printed. In this case the width is 3 and so the output string is (excluding the quotes which are just there to illustrate the spaces)

"  a" 

With your code here

printf("%*c",x);

you have passed the length value, but forgotten to actually pass the variable that you want printed.

So this code

return printf("%*c%*c",x ,' ',y,' ');

is basically saying to print the space character but with a minimum width of x characters (with your code x = 3), then print the space character with a minimum of y characters (in your code y = 4).

The result is that you are printing out 7 blank space characters. This length is the return value of printf (and hence your add function) which is confirmed by the output of

Sum = 7

from the printf inside main() .

If you change your code to

return printf("%*c%*c",x ,'a',y,'b');

you would see the string (obviously excluding the quotes)

"  a    b" 

printed which would make what is happening more clear.

Try to print that in the correct way. %d is for printing integer, %c is for printing char.

In your code:

int x=3;
printf("%*c",x);

The x is how much spaces the char will get, you write 3. But you didn't put the char you want to print, so it print garbage.

When you write:

printf("%*c",x,' ');

You printing space ' ' char inside 3 chars space. Same thing when you do
printf("%*c",x, ' ',y,' '); - just 7 blank spaces. The result is correct because printf returns how many characters it writes.

Look here for extra printf formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM