Confusion over printf statement

So, I ran 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 it may not seem that he understands how the next operator works.

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

So, I tried to write simple code

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

and I got a weird special character (some spaces in front of it) as output

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

I do not get a way out. I have no idea what's going on? Please help. Thanks.

+3
source share
2 answers

This code

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

uses the minimum character width that can be set for each input parameter on printf .

In the above example, the character a is printed, but it is indicated that the minimum width will be x characters, so the output will be the character a , which is preceded by 2 spaces.

The * printf tells printf that the width of the portion of the output string formed from this input parameter will be x minimum character width, where x must be passed as an additional argument / strong> to the variable to be printed. Extra width (if required) is formed from spaces displayed before the variable to be printed. In this case, the width is 3, and so the output string (excluding the quotation marks that just exist to illustrate the spaces)

 " a" 

With code here

 printf("%*c",x); 

you passed the length value but forgot to actually pass the variable you want to print.

So this code

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

basically says to print a space character, but with a minimum character width x (with code x = 3), then print a space character with a minimum character y (in your code y = 4).

As a result, you type 7 spaces. This length is the return value of printf (and therefore your add function), which is confirmed by the output

 Sum = 7 

from printf inside main() .

If you change your code to

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

you will see a line (obviously excluding quotation marks)

 " ab" 

which will make what happens more clearly.

+4
source

Try to print it correctly. %d is for printing integers, %c is for printing char.

In your code:

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

x - how many spaces there will be char, you write 3. But you did not put the char you want to print so that it prints garbage.

When you write:

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

You print the space ' ' char inside 3 characters. Same thing when you do printf("%*c",x, ' ',y,' '); - total 7 spaces. The result is correct because printf returns the number of characters it writes.

Look here for additional printf formats.

+2
source

Source: https://habr.com/ru/post/1234187/


All Articles