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?
\bis 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).