specdrake
specdrake

Reputation: 84

Strange behaviour of '\b' escape sequence with '\n' in printf

If I understand correctly \b escape sequence moves the active cursor position to the left and \n inserts a newline at the cursor position. But the following example is confusing.

λ> cat hello.c                               
#include <stdio.h>

int main()
{
  printf("hello,world\b\b\b\b\bWOR");
  return 0;
}

λ> cc hello.c && ./a.out
hello,WORλ> 
λ> cat hello.c          
#include <stdio.h>

int main()
{
  printf("hello,world\b\b\b\b\bWOR\n");
  return 0;
}

λ> cc hello.c && ./a.out                     
hello,WORld
λ> 

In the first example, \b\b\b\b\b moves the cursor five positions to the left (after ,) and inserts W followed by O and R and the characters in the original string after , are omitted. But, in the second example, usage of \n alters the behaviour of b in an unexpected way. The characters in the original string are overwritten and \n is inserted at the end, rather than at the cursor position. Can someone please explain this behaviour? (Or is it terminal dependent? I have tried on two different terminals.)

Upvotes: 1

Views: 330

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224596

In the first example, \b\b\b\b\b moves the cursor five positions to the left (after ,) and inserts W followed by O and R and the characters in the original string after , are omitted.

No, that is not what happens. First, “hello,world” is written. Then the five \b characters move the cursor position to the “w”. Then “WOR” is written, leaving “hello,WORld” in the display. Then your program ends, and the command-line shell resumes executing. It prints its prompt, “λ> ”. That overwrites the “ld”, leaving “hello,WORλ> ” in the display.

But, in the second example, usage of \n alters the behaviour of b in an unexpected way. The characters in the original string are overwritten and \n is inserted at the end, rather than at the cursor position.

Again, no. “hello,world” is written, the \b characters move the cursor to “w”, then “WOR” is written, and we again have “hello,WORld” in the display. Then the \n advances the display to the next line, leaving “hello,WORld” in the previous line.

Upvotes: 4

Related Questions