Ant's Ant's - 4 days ago 6
C Question

What's the Use of '\r' escape sequence?

I have C code like this:

#include<stdio.h>
int main()
{
printf("Hey this is my first hello world \r");
return 0;
}


I have used the
\r
escape sequence as an experiment. When I run the code I get the output as:

o world


Why is that, and what is the use of
\r
exactly?

If I run the same code in an online compiler I get the output as:

Hey this is my first hello world


Why did the online compiler produce different output, ignoring the
\r
?

Answer

\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.

Tom Zych figured why the output of your program is o wolrd while the \r is at the end of the line and you don't print anything after that:

When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world.

The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r has no effect.

See https://en.wikipedia.org/wiki/Carriage_return

Here is a usage example of \r:

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

int main()
{
        char chars[] = {'-', '\\', '|', '/'};
        unsigned int i;

        for (i = 0; ; ++i) {
                printf("%c\r", chars[i % sizeof(chars)]);
                fflush(stdout);
                usleep(200000);
        }

        return 0;
}

It repeatedly prints the characters - \ | / at the same position to give the illusion of a rotating | in the terminal.

Comments