91

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?

1

8 Answers 8

144

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

7
  • could you say in detail? move the cursor? What it means? then how could I get as o world?
    – Ant's
    Sep 10, 2011 at 16:13
  • 9
    Super :D the example program you gave is perfect! +1
    – Ant's
    Sep 10, 2011 at 16:44
  • could you explain what does usleep does?
    – Ant's
    Sep 10, 2011 at 16:45
  • 2
    usleeps pauses the program for a given number of microseconds Sep 10, 2011 at 16:58
  • You need an fflush in there somewhere... And i should be unsigned of the program will eventually invoke UB when it overflows. Sep 10, 2011 at 17:10
27

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.

2
  • +1 for figuring out that OP was omitting the part about the command prompt having been printed over top of the output. Sep 10, 2011 at 16:18
  • Well, I don't know that it was. It's just a reasonable guess.
    – Tom Zych
    Sep 10, 2011 at 16:18
14

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.

7

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

3
  • 1
    Mac OS <= 9 used \r, but OS X is Unix based and so uses \n.
    – ughoavgfhw
    Sep 10, 2011 at 16:18
  • 2
    Don't confuse line termination sequence of files and how the interactive shell interprets the '\r' or '\n' characters. These are two completely different topics. Sep 10, 2011 at 17:01
  • 1
    If this is true, then I really learned something new today. In my opinion at least both topics are closely related, since as in Unix I/O ports, STDIN and STDOUT are just files and C++ streams can be used for files as well as console output. And afaik std::endl is defined as \n, \r or \r\n depending on the system. But thanks for the advise, I'll take a look into that. I'd appreciate it if you could hint me to some source that specifies the difference.
    – Nornagest
    Sep 10, 2011 at 17:16
2

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.

2
  • Using the compiler available in Ubuntu package.
    – Ant's
    Sep 10, 2011 at 16:18
  • Just use \n. The \r is not needed, on any system. Silly systems that think it is still needed will insert one when they see a \n. Sep 10, 2011 at 16:48
2

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

2
  • 2
    How did you get 3k rep without knowing the difference between a slash and a backslash? O_o Sep 10, 2011 at 17:11
  • 3
    Sorry, I was looking at my monitor in a mirror. :| I corrected the typo. Sep 11, 2011 at 1:42
2

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");
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.