1

Consider the following code for demonstration purpose:

# include <stdio.h>

int main()
{
   printf("Hello World\b\b\b"); //Erases 3 characters from "Hello World"
   printf("Hello World\n\b\b\b"); //Nothing is erased
   return 0;
}

Can someone tell me why backspace doesn't work after a new line?

Abhay Aravinda
  • 878
  • 6
  • 17
  • 3
    The behavior of `\b` is up to your terminal or output device, not C itself – that other guy Mar 18 '20 at 23:28
  • Backspace won't go past the beginning of the line. – Barmar Mar 18 '20 at 23:30
  • 3
    Printing backspace doesn't erase anything. They just get overwritten by the next output. – Barmar Mar 18 '20 at 23:31
  • @usr2564301 That's related, but doesn't explain what happens at the beginning of the line. – Barmar Mar 18 '20 at 23:46
  • "The backspace doesn't delete anything, it moves the cursor to the left". At the beginning of a line the cursor can't move further left. (On a test sample of '1', my own terminal console, at least.) – Jongware Mar 18 '20 at 23:54

1 Answers1

2

Backspace doesn't erase anything. It merely repositions the output cursor to the previous place on the line.

The characters only seem to be erased if you then print something else. The new output will replace whatever was there before. But if you print fewer characters than you backspaced over, it will only overwrite as many characters as you print. So if you print

12345\b\b\b67

the visible result will be

12675

If you don't print anything after the backspaces nothing gets erased because you didn't overwrite them.

Backspace doesn't back up to a previous line; when the cursor is at the beginning of the line, it has no effect.

The above describes the behavior of typical video consoles and terminal emulators. The actual result of control characters depends on the device. For instance, hardcopy printers usually overlay the characters -- underlining is done by writing an underline, backspace, then the character that should be underlined; you can't erase on a hardcopy device.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    You can add information from C 2018 5.2.2 2: “Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.” – Eric Postpischil Mar 18 '20 at 23:45