3

I have the following program in which I'm trying to understand the functioning of \b escape sequence.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int disp(char *a) 
{
    return printf("%s", a); 
}

int main(void)
{
    char *s = "Hello\b\b";

    printf(" %d\n", disp(s));
    printf("%s %d\n", s, strlen(s));

    return 0;
}

Output:

$ ./a.out 
Hel 7
Hel 7
$ 

As expected Hello\b\b prints Hell but the strlen() returns 7 which includes the two \b characters.

As per C99 5.2.2 \b is defined as follows:

\b (backspace) 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.

How is \b interpreted in string-related functions like strlen()? Are \b and other escape sequences resolved at compile time or run time?

thiton
  • 35,651
  • 4
  • 70
  • 100
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98

4 Answers4

9

\b is a character just like any other in your program. It only becomes special when the terminal sees it.

The characters below ASCII 32 are called "control characters" for a reason: They are a signal to the display device, i.e. your terminal or console, that it should do something special, like beep (\a), move the cursor backwards (\b) or to the next tab stop (\t).

thiton
  • 35,651
  • 4
  • 70
  • 100
1

Resolved during run time. The length of the string includes the \b length, but the "rendering engine", the console, is displaying/executing the backspace.

Matt H
  • 6,422
  • 2
  • 28
  • 32
1

strlen() will go over the char pointer given as an argument until it finds 0.

But \b is not 0, this is why you see what you see.

The action linked to this character, however, is linked to your output device.

fge
  • 119,121
  • 33
  • 254
  • 329
1

\b only affects output. All string functions will still see it as a character. When your "Hello\b\b", 7 get displayed, this is what happens (with _ signifying the cursor position):

H_
He_
Hel_
Hell_
Hello_
Hell_o  - cursor moves backwards
Hel_lo  - cursor moves backwards
Hel _o  - the space overwrites the "l"
Hel 7_  - the "7" overwrites the "o"
Amadan
  • 191,408
  • 23
  • 240
  • 301