Ant's Ant's - 1 year ago 58
C Question

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

I have C code like this:

int main()
printf("Hey this is my first hello world \r");
return 0;

I have used the
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

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

Answer Source

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


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)]);

        return 0;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download