1

when \b used inside string.

int main (void)
{
    printf("asdfhjk\bll");
    return 0;
}

output:

asdfhjll

when \b used at the end of the string.

int main (void)
{
    printf("asdfhjkll\b");
    return 0;
}

output:

asdfhjkll

why the last character l is not removed by \b. according to the working of \b, the character preceding the \b is removed. it works fine when used in the middle of the string, but not when used at the end. why?

Priya
  • 334
  • 3
  • 8
aambazinga
  • 53
  • 7
  • Similar question: https://stackoverflow.com/questions/2856344/backspace-character-weirdness –  Jul 21 '18 at 18:36

2 Answers2

4

The character \b is a backspace character. It moves the cursor one position backwards without writing any character to the screen.

Consider your first example: asdfhjk\bll. Before "printing" the backspace character, the screen looks like this:

asdfhjk
       ^

... where ^ indicates the cursor position. And after printing \b, it goes this

asdfhjk
      ^

The the last two characters overwrite k:

asdfhjll
        ^

For the second example asdfhjkll\b. before printing \b:

asdfhjkll
         ^

and after:

asdfhjkll
        ^

No character is erased, but the cursor has been shifted one char backwards. If you print anything else, the last l gets overridden.

iBug
  • 35,554
  • 7
  • 89
  • 134
1

\b means "move the output position one character backwards." So when you output e.g. x\by, x is written, then the output cursor is rewound before the x just written, and then the y overwrites the x.

However, when there's no output following the \b, the cursor simply remains where it was. Further output would then overwrite the last visible character written.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • 1
    okay... so although cursor is at the position of last 'l', it will remain there without doing any harm. had it been in the middle, other character would have come and overwrite it.. right? – aambazinga Jul 21 '18 at 14:56