This is my C code, compiled with gcc.
#include<stdio.h>
int main()
{
int a=1;
switch(a)
{
int x=10;
case 1:
printf("%d\n",printf("%d\b",x));
break;
default:
printf("%d\n",printf("%d\b",x));
}
return 0;
}
printf() is supposed to return the number of elements it printed successfully.
printf("%d\b", x) should have printed 10 by itself(since the \b takes the printing pointer one step behind (to the digit 0 in 10) and there is nothing to print after that.
So it should have just printed 10. That is 2 characters. Now the outer printf would display 2.
The output should have been 102.
The output I actually see is 2.
And in case of nested printfs is the printing pointer position remembered? I mean, if there is a \b in the inside printf , it would take the printing pointer one step behind. And when the control now goes to the outer printf, is that changed position remembered? Will it overwrite over that last character?
prints the characters
'1','0'(because x==10) and\b. The\bis a backspace character; if you print to a terminal, it will print10and then move the cursor back one column.A call to
printfreturns the number of characters it printed; in this case, the result is 3 (yes,'\b'counts as a character).The inner
printfcall works as I explained above, and returns 3. The outerprintfcall prints"3\n".So the entire statement will print:
The
'\b'causes the3to be replace the0on the screen, so the final displayed result (when I run the program on my system) is:If I pipe the output through
cat -v, I get:where
^Hrepresents the backspace character.EDIT :
The question was just edited, and the modified program’s behavior is quite different. The switch statement causes control to jump past the declaration
int x = 10;, but into the scope in whichxis declared. As a result,xis uninitialized whenprintfis called. This causes undefined behavior, and most likely garbage output (I just got-1217572876^H12). Ifxhappens to be0, I suppose you’d get0^H2, which would look like2.Whatever you’re trying to do, please find a better way to do it.