Adding using printf in C

on the network: using printf add two numbers (without using any operator), for example:

 main() { printf("Summ = %d",add(10,20)) return 0; } int add(int x,int y) { return printf("%*d%*d",x,' ',y,' '); } 

Can someone explain how this works:

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

Note. This fails when I call "sum" as follows:

 sum(1,1) or sum(3,-1) 
+6
source share
3 answers

There are two main concepts here:

  • printf() returns the number of characters printed.
  • The format specifier %*d forces printf() to read two integers from its arguments and use the first to set the field width used to format the second (as a decimal).

Thus, the values ​​added are used as the width of the field, and printf() then returns the sum.

I am not sure about the actual formatting of the d space character at the moment. This looks strange, I would go with an empty string instead:

 static int sum(unsigned int a, unsigned int b) { return printf("%*s%*s", a, "", b, ""); } int main(void) { unsigned int a = 13, b = 6; int apb = sum(a, b); printf("%d + %d = %d?\n", a, b, apb); return 0; } 

The above work and correctly calculates the sum as 19 .

+8
source

printf returns the number of characters printed.

Here it is used in the add function to generate a string consisting of 10 + 20 spaces using a format string.

So printf in the add function will return 30 .

Then this result is simply printed using printf (its main purpose).

Note: this may be obvious, but this use of printf should be avoided. It is very dirty because it generates useless results. Imagine: add(10000,10000) ...

+2
source

Firstly, printf returns the number of characters it prints.

Secondly, in the format specifier %*d , * means the minimum number of characters to print, but the width does not apply to the format string itself, but from an additional argument.

All together, the task is being executed, but it will not work on small numbers, such as 1 due to %d in the format specifier, the best solution might be:

 ("%*c%*c", a, ' ', b,' '); 
+1
source

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


All Articles