[c++] 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?

This question is related to c++ c escaping carriage-return

The answer is


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


This is from antiquated technology: The old fashion typewriter style of printer. There was a roller (platen) that advanced the paper and a print head that hammered a metal key against an ink fabric.

\r Return the print head to the left side.

\n Advance the platen one line.

If the \n was not issued, you would type over what was on a line (used mostly for underlining text).


The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.


\r move the cursor to the begin of the line.

Line breaks are managed differently on different systems. Some only use \n (line feed, e.g. Unix), some use (\r e.g. MacOS before OS X afaik) and some use \r\n (e.g. Windows afaik).


The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.

Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.

Hope this helps!

PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.


To answer the part of your question,

what is the use of \r?

Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:

fprintf(socket, "RCPT TO: %s\r\n", recipients);

Or, when a FTP server replies with a permission-denied error:

fprintf(client, "550 Permission denied\r\n");

It is quite useful, when you are running on the unix platform, and need to create a text file which will be opened on the dos platform.

Unix uses '\n' as its line terminator, and dos uses '\r\n' as its line terminator, so you can use it to create a dos text file.


As amaud576875 said, the \r escape sequence signifies a carriage-return, similar to pressing the Enter key. However, I'm not sure how you get "o world"; you should (and I do) get "my first hello world" and then a new line. Depending on what operating system you're using (I'm using Mac) you might want to use a \n instead of a \r.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to escaping

Uses for the '&quot;' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?

Examples related to carriage-return

Create Carriage Return in PHP String? What is the difference between a "line feed" and a "carriage return"? How can I insert new line/carriage returns into an element.textContent? What are the differences between char literals '\n' and '\r' in Java? What's the Use of '\r' escape sequence? Carriage return and Line feed... Are both required in C#? Find and replace - Add carriage return OR Newline In C#, what's the difference between \n and \r\n? See line breaks and carriage returns in editor What are carriage return, linefeed, and form feed?