796

What’s the difference between \n (newline) and \r (carriage return)?

In particular, are there any practical differences between \n and \r? Are there places where one should be used instead of the other?

TRiG
  • 10,148
  • 7
  • 57
  • 107
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • 4
    All the answers are fairly predictable, but I'd be interested to know if there are any PRACTICAL differences between \n and \r. Are there places where one should be used over the other? – Vlad the Impala Nov 19 '09 at 05:26
  • 14
    well, yes, text files with only LF (newline) won't be seen as terminated in some Windows applications, and text files terminated with CRLF will appear to have extra characters if opened in some Linus applications. – pavium Nov 19 '09 at 05:30
  • 4
    yes, \r is used by some linux console apps to do rotating line animation. – Murali Nov 19 '09 at 05:31
  • 10
    Is \r really still the normal Mac EOL? I'm sure it was for "Classic" Mac, but I had thought OS X had Unixified. (Shows how familiar I am with Macs, eh?) – John Y Nov 19 '09 at 05:34
  • 19
    historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the page. – karthik gorijavolu Nov 16 '12 at 12:18

12 Answers12

1028

In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).

But seriously, there are many:

  • in Unix and all Unix-like systems, \n is the code for end-of-line, \r means nothing special
  • as a consequence, in C and most languages that somehow copy it (even remotely), \n is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)
  • in old Mac systems (pre-OS X), \r was the code for end-of-line instead
  • in Windows (and many old OSs), the code for end of line is 2 characters, \r\n, in this order
  • as a (surprising;-) consequence (harking back to OSs much older than Windows), \r\n is the standard line-termination for text formats on the Internet
  • for electromechanical teletype-like "terminals", \r commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation), \n commands the roller to roll up one line (a much faster operation) -- that's the reason you always have \r before \n, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation.
  • for character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller;-)

In practice, in the modern context of writing to a text file, you should always use \n (the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use \r is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-).

AdrianHHH
  • 13,492
  • 16
  • 50
  • 87
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 16
    To add to the history in this answer: as line speeds increased from 10 characters per second, it took more than 2 characters worth of time for the carriage to return and extra harmless characters (typically NUL i.e. `\0`) were added after the `\n` to allow the extra time. This was handled transparently by the OS so you won't find any traces of it in legacy code. – Mark Ransom Jul 19 '12 at 15:47
  • 12
    How is windows a 'weird' operating system? – mailmindlin Oct 30 '14 at 21:18
  • 42
    @mailmindlin -- you ask "How is windows a 'weird' operating system?". Answer: in more ways than I can easily count (while wearing socks, so toes not allowed:-). All other surviving OS's are Unix-based... Windows's the one out, WAY out in many ways. In this specific Q's context -- it's the only one positing TWO bytes (\n\r) as the canonical line-end... for no sensible reason except the ancient-historical ones explained elsewhere on the thread... every other OS has a single char a5 line-end (99%+ of them `\n'). – Alex Martelli Dec 04 '14 at 04:56
  • Thanks - but can you please cite a source for this: " \r\n is the standard line-termination for text formats on the Internet" And if this is the case, I'm not sure why posting `textarea` with newlines from Chrome shows (via packet sniffer) that data sent to server is `\n` and not `\r\n` (doesn't seem very standard) – nothingisnecessary Jan 20 '16 at 20:24
  • 2
    @nothingisnecessary: For example, https://tools.ietf.org/html/rfc5322, which replaced RFC 2822, defining the format of e-mail messages. – Keith Thompson Jan 20 '16 at 20:34
  • Great explanation .. +1 .. Just one thing, when you say *Unix* or *Linux* or *Mac* or *Windows*, are you talking about which OS? The OS of user who uses of my website? Or the OS of server which my website has uploaded on it? – Shafizadeh Feb 22 '16 at 11:25
  • 1
    @Shafizadeh, what part of (and I quote my answer) "\r\n is the standard line-termination for text formats on the Internet" is unclear to you? A website lives on the Internet, you know that, right? – Alex Martelli Feb 22 '16 at 19:44
  • 4
    A small advice to all who will write a parser of some sort at some point in their lives - never forget to properly handle the ending of lines. I had some pretty nasty experience with that just because I forgot about the `\r` (I'm using Linux). Once I started parsing what seemed to be a valid file my parser failed because the file I was parsing has been created in Windows. :D The main problem in all that is that neither `\n` or `\r` are visible in the sense that for example `a`, `.`, `(` etc. characters are. – rbaleksandar Feb 26 '16 at 11:54
  • 7
    "All other surviving OS's are Unix-based" not surprising considering they are all just some permutation of Unix. That's like saying vanilla is a weird ice cream flavour, because 100 people decided to sprinkle their chocolate ice cream with 100 different toppings and thus created 100 different flavours. I'm really getting tired of people comparing WIndows and Unix like they are supposed to be alternatives to each-other. That's like comparing a sports car to a tractor because they are both motor vehicles. And then claiming one is better than the other, period. – J. Doe Feb 19 '18 at 11:03
  • technically, it's a difference of `11` as it's stored in binary. – Armstrongest Sep 20 '22 at 22:48
188

Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the page.

Sam
  • 7,252
  • 16
  • 46
  • 65
tster
  • 17,883
  • 5
  • 53
  • 72
  • 26
    Perhaps not a terribly practical answer to a computer question, but the historical tidbit gets an upvote from me anyway. – John Y Nov 19 '09 at 05:29
  • 2
    Imagine \r to be similar to when you push the typing part of your physical typing machine to the left aka. return. – Jo Smo Oct 24 '16 at 09:04
  • 3
    \n doesn't move the carriage down, it turns the roller to move the paper UP. – Roddy Nov 24 '16 at 11:31
  • 11
    All movement is relative. The paper is my world, and relative to it, the carriage is moving down :P – tster Nov 29 '16 at 22:44
  • 5
    FWIW, \r can still be a "Carriage Return" on modern systems. Consider this C code ```printf("abcdefghijlm\rNOP\n");``` Compiled with gcc-8 on OpenSuSe and run on a terminal results in this output ```NOPdefghijlm```. The \r (carriage return) in the string results in the cursor moving to the beginning of the line (carriage) and the characters following the \r (i.e. "NOP") overwrite what was previously there (i.e. the "abc")! You can achieve similar "carriage movement" with backspace (\b) as in ```printf("abcdefghijlm\b\bNOP\n");``` which produces ```abcdefghijNOP``` – GMc May 12 '19 at 10:23
  • a TLDR version, nice – Kevin Chandra Oct 02 '20 at 07:00
65

Two different characters.

\n is used as an end-of-line terminator in Unix text files

\r Was historically (pre-OS X) used as an end-of-line terminator in Mac text files

\r\n (ie both together) are used to terminate lines in Windows and DOS text files.

nishanthshanmugham
  • 2,967
  • 1
  • 25
  • 29
pavium
  • 14,808
  • 4
  • 33
  • 50
  • 2
    Notice that there are/was computers that used \n\r as end of line marker when you pressed the ENTER key, Like Acorn and RISC OS. – Anders Apr 16 '14 at 17:40
  • 14
    To clarify: `\r` hasn't been the line-ending on a Mac for a long time. With the release of Mac OS X in 2001 (which is Unix-based), `\n` is now used. – jbbuckley Jul 25 '15 at 01:21
  • 7
    But there still some applications using `\r` - e.g. MS Office 2011 Excel: Saving a CSV (with all default settings) - will save an ISO-8859-1 encoded file with `\r`-line endings. – CodeBrauer Jul 11 '17 at 12:48
37

Since nobody else mentioned it specifically (are they too young to know/remember?) - I suspect the use of \r\n originated for typewriters and similar devices.

When you wanted a new line while using a multi-line-capable typewriter, there were two physical actions it had to perform: slide the carriage back to the beginning (left, in US) of the page, and feed the paper up one notch.

Back in the days of line printers the only way to do bold text, for example, was to do a carriage return WITHOUT a newline and print the same characters over the old ones, thus adding more ink, thus making it appear darker (bolded). When the mechanical "newline" function failed in a typewriter, this was the annoying result: you could type over the previous line of text if you weren't paying attention.

nothingisnecessary
  • 6,099
  • 36
  • 60
  • 4
    The ASCII standard for newline is \r\n. (Apart from a brief interval when Bell Telephone got control of the standards committee). In return for the telephone monopoly, Bell Telephone gave up the messaging business (telegram, teletype), and did not care about existing use of the standard. HTTP, HTML, PCDOS and MSDOS used the ASCII standard. Bell Telephone chose to go non-standard for unix because they had no existing business to be compatible with. – david Jul 26 '16 at 11:21
18

Two different characters for different Operating Systems. Also this plays a role in data transmitted over TCP/IP which requires the use of \r\n.

\n Unix

\r Mac

\r\n Windows and DOS.

Ziad Amerr
  • 163
  • 1
  • 14
a432511
  • 1,907
  • 4
  • 26
  • 48
  • 13
    I think you are confusing with applicative protocols, TCP/IP has no idea of \n and \r . – jean-loup Jul 23 '14 at 13:27
  • 9
    TCP/IP does not require the use of \r\n. Various protocols based on Telnet require it, including SMTP, POP3, FTP, HTTP, ... – user207421 Aug 08 '14 at 23:31
13

To complete,

In a shell (bash) script, you can use \r to send cursor, in front on line and, of course \n to put cursor on a new line.

For example, try :

echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"
  • The first "echo" display AA--AA
  • The second : AA--AABB
  • The last : BB--AABB

But don't forget to use -en as parameters.

Akarun
  • 3,220
  • 2
  • 24
  • 25
13

In windows, the \n moves to the beginning of the next line. The \r moves to the beginning of the current line, without moving to the next line. I have used \r in my own console apps where I am testing out some code and I don't want to see text scrolling up my screen, so rather than use \n after printing out some text, of say, a frame rate (FPS), I will printf("%-10d\r", fps); This will return the cursor to the beginning of the line without moving down to the next line and allow me to have other information on the screen that doesn't get scrolled off while the framerate constantly updates on the same line (the %-10 makes certain the output is at least 10 characters, left justified so it ends up padded by spaces, overwriting any old values for that line). It's quite handy for stuff like this, usually when I have debugging stuff output to my console screen.

A little history

The /r stands for return or carriage return which owes it's history to the typewriter. A carriage return moved your carriage all the way to the right so you were typing at the start of the line.

The /n stands for new line, again, from typewriter days you moved down to a new line. Not nessecarily to the start of it though, which is why some OSes adopted the need for both a /r return followed by a /n newline, as that was the order a typewriter did it in. It also explains the old 8bit computers that used to have Return rather than Enter, from carriage return, which was familiar.

Neil Roy
  • 603
  • 5
  • 13
13
  • \r: Carriage R̲eturn CR—returns the carriage to the start of the line
  • \n: Line feed (N̲ew Line) LF—feed the paper up one line

In the context of screen output:

  • CR: returns the cursor to the start of the current line
  • LF: moves the cursor down one line

For example:

Hello,\nworld\r!

is supposed to render on your terminal as:

Hello,
!     world

Some operating systems may break compatibility with the intended behavior, but that doesn't change the answer to the question "Difference between \n and \r?".

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
5

What’s the difference between \n (newline) and \r (carriage return)?

In particular, are there any practical differences between \n and \r? Are there places where one should be used instead of the other?


I would like to make a short experiment with the respective escape sequences of \n for newline and \r for carriage return to illustrate where the distinct difference between them is.

I know, that this question was asked as language-independent. Nonetheless, We need a language at least in order to fulfill the experiment. In my case, I`ve chosen C++, but the experiment shall generally be applicable in any programming language.

The program simply just iterates to print a sentence into the console, done by a for-loop iteration.


Newline program:

#include <iostream>

int main(void)
{
    for(int i = 0; i < 7; i++)
    {
       std::cout << i + 1  <<".Walkthrough of the for-loop \n";   // Notice `\n` at the end.
    }
    return 0;
}

Output:

1.Walkthrough of the for-loop
2.Walkthrough of the for-loop
3.Walkthrough of the for-loop
4.Walkthrough of the for-loop
5.Walkthrough of the for-loop
6.Walkthrough of the for-loop
7.Walkthrough of the for-loop

Notice, that this result will not be provided on any system, you are executing this C++ code. But it shall work for the most modern systems. Read below for more details.


Now, the same program, but with the difference, that \n is replaced by \r at the end of the print sequence.

Carriage return program:

#include <iostream>

int main(void)
{
    for(int i = 0; i < 7; i++)
    {
       std::cout << i + 1  <<".Walkthrough of the for-loop \r";   // Notice `\r` at the end.
    }
    return 0;
}

Output:

7.Walkthrough of the for-loop 

Noticed where the difference is? The difference is simply as that, when you using the Carriage return escape sequence \r at the end of each print sequence, the next iteration of this sequence do not getting into the following text line - At the end of each print sequence, the cursor did not jumped to the *beginning of the next line.

Instead, the cursor jumped back to the beginning of the line, on which he has been at the end of, before using the \r character. - The result is that each following iteration of the print sequence is replacing the previous one.

*Note: A \n do not necessarily jump to the beginning of following text line. On some, in general more elder, operation systems the result of the \n newline character can be, that it jumps to anywhere in the following line, not just to the beginning. That is why, they rquire to use \r \n to get at the start of the next text line.


This experiment showed us the difference between newline and carriage return in the context of the output of the iteration of a print sequence.

When discussing about the input in a program, some terminals/consoles may convert a carriage return into a newline implicitly for better portability, compatibility and integrity.

But if you have the choice to choose one for another or want or need to explicitly use only a specific one, you should always operate with the one, which fits to its purpose and strictly distinguish between.

Community
  • 1
  • 1
4

Just to add to the confusion, I've been working on a simple text editor using a TextArea element in an HTML page in a browser. In anticipation of compatibility woes with respect to CR/LF, I wrote the code to check the platform, and use whichever newline convention was applicable to the platform.

However, I discovered something interesting when checking the actual characters contained in the TextArea, via a small JavaScript function that generates the hex data corresponding to the characters.

For the test, I typed in the following text:

Hello, World[enter]

Goodbye, Cruel World[enter]

When I examined the text data, the byte sequence I obtained was this:

48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 0a 47 6f 6f 64 62 79 65 2c 20 43 72 75 65 6c 20 57 6f 72 6c 64 0a

Now, most people looking at this, and seeing 0a but no 0d bytes, would think that this output was obtained on a Unix/Linux platform. But, here's the rub: this sequence I obtained in Google Chrome on Windows 7 64-bit.

So, if you're using a TextArea element and examining the text, CHECK the output as I've done above, to make sure what actual character bytes are returned from your TextArea. I've yet to see if this differs on other platforms or other browsers, but it's worth bearing in mind if you're performing text processing via JavaScript, and you need to make that text processing platform independent.

The conventions covered in above posts apply to console output, but HTML elements, it appears, adhere to the UNIX/Linux convention. Unless someone discovers otherwise on a different platform/browser.

DeyaEldeen
  • 10,847
  • 10
  • 42
  • 75
David Edwards
  • 794
  • 8
  • 13
0
#include <stdio.h>

void main()
{
  int countch=0;
  int countwd=1;

  printf("Enter your sentence in lowercase: ");
  char ch='a';
  while(ch!='\r')
  {
    ch=getche();
    if(ch==' ')
      countwd++;
    else
      countch++;
  }

  printf("\n Words = ",countwd);

  printf("Characters = ",countch-1);

  getch();

}

lets take this example try putting \n in place of \r it will not work and try to guess why?

karthik gorijavolu
  • 860
  • 3
  • 14
  • 28
  • 2
    This only works if your underlining OS sends \r\n when you press the ENTER key, like MS DOS, DECS TOPS-10, CP/M, RT-11 etc. In OS:es like Multic, Unix and Unix-like(Linux, Minix etc) BeOS, RISCOS etc ENTER key only send you a \n character. – Anders Apr 16 '14 at 17:37
  • 1
    ahh yes the good old days when keyboards used to have both `Return` and `Enter`. Even my modern wireless keyboard still shows the down-and-back arrow on the old `Return` key (which is now titled "Enter" to be consistent with the numeric keypad's `Enter` key, which does not show the arrow) – nothingisnecessary Oct 05 '16 at 22:57
  • In "modern languages", such errors / problematic code can still be evident when splitting lines on `\r\n` instead of `\r?\n` .. such can be found in windows code bases in language runtimes that don't offer a virtual newline. – user2864740 Jan 22 '21 at 22:20
-1

I wrote an example of a carriage return based on Ian Boyd's answer.

This Python script will print characters in the same line by returning the carriage to the start of the line.

\r

import time
for i in "I'm", "N", "Ne", "Neo":
    time.sleep(1)
    print(i, end='\r')

\n

import time
for i in "I'm", "N", "Ne", "Neo":
    time.sleep(1)
    print(i, end='\n')
Constantin Hong
  • 701
  • 1
  • 2
  • 16