The Illusion of Erasure: What \b, \r, and \n Actually Do to Your Screen
DEV Community

The Illusion of Erasure: What \b, \r, and \n Actually Do to Your Screen

Compile vs. Runtime

  • Compile: Translate source code (the code written in the programming language) to machine code (0's and 1's, aka binary, aka the only language a computer actually understands).
  • Runtime: From the point we open a program to the point of it closing / doing everything it's supposed to do.

What \n, \r, and \b Actually Do

  • \n means move the cursor to the next line.
  • \r means move the cursor to the very first space of the current line.
  • \b means move the cursor back by one space.

NONE of it ever actually deletes, pulls, or moves the text written on the screen. Once it's there, it is TOTALLY there.

Example with \b

If we write code like:

#include <stdio.h>
int main(void) {
    printf("Hello Alexa\b\n");
}

The result is something like this: Hello Alexa

The program prints out "Hello, Alexa"; then the cursor sits on top of "a" (\b means go back a space). But when you give the command \n, it doesn't move the "a" to the next line - only the cursor goes to the next line. It CAN NOT drag "a" with it to the new line. The printed lines are kinda stuck on the screen.

Example with \r

Same happens if we type \r. It doesn't erase ANYTHING. It moves the cursor to "H", and when \n comes it just moves the CURSOR to the next line. "H" stays in the same place.

The Illusion of Erasure: Overwriting

The only way we can give an illusion of erasure is if we do something called "Overwrite it". For example:

#include <stdio.h>
int main(void) {
    printf("Hello World\r");
    printf("B");
}

The result will be: Bello World

The cursor moves to "H" and then overwrites it - aka write a "B" over the "H". The computer has no more memory of the "H" there on the screen. It is deleted.

If we do the same with \b instead of \r, then we'll see the result Hello WorlB.

How the Compiler Reads Spaces

The compiler can read the spaces between the words you wanna type and the backslash commands. For example, if you type:

#include <stdio.h>
int main(void) {
    printf("Hello World \b");
    printf("B");
}

The result will be: Hello WorldB

Because:

  • First we print out "Hello World" (with a space).
  • When there is a \b, the cursor comes right beside the letter "d".
  • It prints the letter "B".

The compiler can even read the spaces between two backslash commands. For example, if you type \r space \n, then the compiler will act accordingly. Even your spaces matter when using these.

Comments

No comments yet. Start the discussion.