4

Why do we use \r and \b in C? I know that \b makes "hello\bworld" into "hellworld". but we can just write "hellworld" instead of "hello\bworld". So, what purpose does it serves in a program? This question describes what \b do , but doesn't clarify why it is used.

Orni Sen
  • 5
  • 3
Miraz
  • 343
  • 3
  • 15
  • 1
    You wouldn't use them in a single string like that, but you can use them to overwrite something you wrote earlier. – Barmar Oct 27 '20 at 06:27
  • It's used as an example. No other reason. – Nikos C. Oct 27 '20 at 06:28
  • 2
    Back in the old days of dot matrix or daisy wheel printers, you used `\r` to move the print head back to the start of the line and you wrote the same text again to get bold, or you could use different text and maybe get images with different intensities. Using `\b` would allow you to do the overstriking one character at a time. Using `\r\n` for line endings is still a part of numerous internet protocols (as well as the line ending on Windows). These days, using `\b` is rare — I don't recall when I last used it, but it might gave been more recent than either `\a` or `\v`. – Jonathan Leffler Oct 27 '20 at 06:33
  • If you implement an application doing some line edition when interacting with the operator, this can be used to move the cursor back and forth, to erase characters and so on. – Rachid K. Oct 27 '20 at 06:34
  • `\r` keeps all stuff in cache so `cout`'s doesn't affect performance. – Алексей Неудачин Oct 27 '20 at 07:58
  • Fun fact, some old Windows NTs could be crashed (the operating system bluescreened and needed to be rebooted) by just printing `\t\b\b ` i.e. tab, 2 backspaces and space at the top left corner of a console window :D (Applies to certain revisions of Windows NT 4 and Windows 2000...) – Antti Haapala -- Слава Україні Oct 27 '20 at 08:06
  • Miraz: I wrote an answer utilizing this today. It's linked in my answer below too, but here: https://stackoverflow.com/a/64555935/6699433 – klutt Oct 27 '20 at 14:02
  • *I know that \b makes "hello\bworld" into "hellworld". but we can just write "hellworld" instead of "hello\bworld".* Not really. Those are two different byte streams and have different results depending on the media written to. – Andrew Henle Oct 27 '20 at 14:08

5 Answers5

5

Its' to a large degree just historical reasons. Many characters can actually be traced back to analogue typewriters! In the past, you had computers with matrix printers instead of monitors. In those days, bold font was achieved by printing something twice in the same location.

For example, in Linux we use the character \n for a new line, but in Windows it is \r\n so what is those characters? Well \n (newline) is to move the head of the typewriter one line down and \r is the carriage return, which returns the typewriter carriage to the beginning of the line.

Many of these characters are not used very much anymore. They are mostly considered legacy. They are not really that useful in modern programming. You can use \b to go back and overwrite stuff that you have previously written, but today you would use libraries like ncurses to achieve the same thing. In the old days, you could actually use these to get pretty exact positioning of stuff, but on modern terminal emulators, that's no longer the case. For instance, old terminals had fixed sizes. The sizes may not have been standardized, but they did not change during runtime and were the same for the same machine every time you run a program.

I could consider using \b and \r if I wanted to write a cli application with some kind of progress bar. Example:

#include <stdio.h>
#include <unistd.h>

int main(void) {
    int n = 0;
    while(n<=100) {
        printf("\rProgress: %d\%", n);
        fflush(stdout);
        sleep(1);
        n+=10;
    }
}

You could achieve the same thing with \b instead of \r, but mostly it's easier to just reprint the whole line. I cannot see any situation where I would use \b in code.

A similar thing can be done if you want to simulate human writing in a text based game. But I would say that these kind are mostly for the case where you don't have the time and/or energy to learn how to use proper modern methods.

Let's look at the first 32 characters in the ascii table:

0   Null char
1   Start of Heading
2   Start of Text
3   End of Text
4   End of Transmission
5   Enquiry
6   Acknowledgment
7   Bell
8   Back Space
9   Horizontal Tab
10  Line Feed
11  Vertical Tab
12  Form Feed
13  Carriage Return
14  Shift Out / X-On
15  Shift In / X-Off
16  Data Line Escape
17  Device Control 1 (oft. XON)
18  Device Control 2
19  Device Control 3 (oft. XOFF)
20  Device Control 4
21  Negative Acknowledgement
22  Synchronous Idle
23  End of Transmit Block
24  Cancel
25  End of Medium
26  Substitute
27  Escape
28  File Separator
29  Group Separator
30  Record Separator
31  Unit Separator

Almost all of these have been replaced by other things. For instance by higher level protocols, like tcp and such, but also by libraries like ncurses. In C, the null character is useful for strings, but it could have been solved in other ways, like making it possible to retrieve the size of an array when it's passed to a function.

klutt
  • 30,332
  • 17
  • 55
  • 95
  • `\b` can be useful when simulating someone writing text and hitting backspace [like this](https://gist.github.com/sepp2k/de8ef4185eecfff65902a05252e26643). That might be something one may want to do in a text-based game for story-telling purposes or as a visual gag. – sepp2k Oct 28 '20 at 12:31
3

You use them to overwrite something you wrote previously. You wouldn't normally use them in the same string, but in different output calls, e.g.

printf("hello");
fflush(stdout); // need to flush because we didn't write a newline
// do some stuff here
printf("\rgoodbye\n"); // This replaces hello
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Those escape sequences are used today mainly for creating some kind of CLI-"GUI", for CLI-"animations", like showing a "loading progress" and some special tricks.

In the past those escape sequences were used mainly to control teleprinter and for punched cards.

For example, for deleting the last punched character on a punch card, you used:

putchar('\b'); putchar(127); /* DEL */.

paladin
  • 765
  • 6
  • 13
1

\ris used to move the cursor in the beginning of above line and \n is used to move the cursor to beginning of next line.

#include <stdio.h>
#include <unistd.h>
#include<iostream>
using namespace std;
int main() {
    cout<<"Hello";
    cout<<"\r";
    cout<<"Gone  ";
}

Above program will not display Hello.

#include <stdio.h>
#include <unistd.h>

int main() {
    int i=0;
    int n=4;
    char pattern[n];
    pattern[0]=(char)179;
    pattern[1]=(char)47;
    pattern[2]=(char)196;
    pattern[3]=(char)92;
    long long int count=0;
    while(count<100000000){
        printf("%c",pattern[i]);
        i=(i+1)%n;
        printf("\r");
        count++;

    }
}

Test it by yourself.

Udesh
  • 2,415
  • 2
  • 22
  • 32
1

\n" for new line "\b" for a backspace, means if u print it, cursor will print and come back 1 character. For example.... cout<<"hello\bHi"; will print "HellHi". because after printing Hello, compiler found a \b escape sequence. so it came 1 character back (at 'o' of Hello) and stat printing Hi from o of Hello..... so u got HellHi instead of HelloHi.

'\r' is used for carriage return to come 1 line back or in start of line.

\b = it's purpose is backspace \r = purpose is carriage return

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.

The cursor is the position where the next characters will be rendered.

So, printing a \r allows to override the current line of the terminal emulator.

Whereas \b is backspace character it takes the cursor one character backward so that when you will type next thing the characters ahead of cursor will be overwritten.

Thus \b illustrates the working of backspace whereas carriage return simply moves the cursor to the starting of the current line.