What is the use of width in the printf() statement? Why is the output 7 in the example below?
Code
int add(int x, int y)
{
return printf("%*c%*c", x, '\r', y, '\r');
}
int main()
{
printf("Sum = %d", add(3, 4));
return 0;
}
Output
Sum = 7
printfreturns the number of characters output.%*cmeans print a character and pad to the width specified by an argument. Soprintf("%*c", 3, '\r')means to print a carriage return with 2 spaces before it.printf("%*c%*c", n, '\r', m, '\r')therefore printsn+mcharacters – that’sn– 1 spaces to pad the first\r,m– 1 spaces to pad the second\r, and the two carriage returns. That’s why it returns 7.A carriage return takes you back to the start of the line, so after printing those
n+mcharacters the next thing printed will appear at the start of the line. That means"Sum = "overwrites the output of the first printf.