Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "backspace" escape character '\b': unexpected behavior?

So I'm finally reading through K&R, and I learned something within the first few pages, that there is a backspace escape character, \b.

So I go to test it out, and there is some very odd behavior:

#include <stdio.h>

main ()
{
    printf("hello worl\b\bd\n");
}

The output is

hello wodl

Can anyone explain this?

like image 502
OregonTrail Avatar asked Jul 22 '11 16:07

OregonTrail


3 Answers

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

like image 75
T.J. Crowder Avatar answered Nov 08 '22 11:11

T.J. Crowder


..........
^ <= pointer to "print head"
            /* part1 */
            printf("hello worl");
hello worl
          ^ <= pointer to "print head"
            /* part2 */
            printf("\b");
hello worl
         ^ <= pointer to "print head"
            /* part3 */
            printf("\b");
hello worl
        ^ <= pointer to "print head"
            /* part4 */
            printf("d\n");
hello wodl

^ <= pointer to "print head" on the next line
like image 128
pmg Avatar answered Nov 08 '22 12:11

pmg


If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

like image 49
Peter K. Avatar answered Nov 08 '22 10:11

Peter K.