The Carriage Return (CR) is a control character in the ASCII (American Standard Code for Information Interchange) character set that moves the cursor or print head to the beginning of the current line without advancing to the next line. It is commonly represented by the escape sequence \r
.
Key Points About Carriage Return (CR):
-
ASCII Code:
- The Carriage Return character has an ASCII code of 13.
- In hexadecimal, its value is 0x0D.
-
Function:
- Historically, in typewriters and early computers, pressing the "Carriage Return" would physically return the print head or cursor to the leftmost position of the line without advancing to the next line.
- On modern computers, its primary role is as a line-control character, used in combination with other characters to signify the end of a line (such as with Line Feed or LF).
-
Usage in Text Formatting:
- Windows: In Windows operating systems, line breaks are typically represented by the combination of Carriage Return (CR) and Line Feed (LF), written as
\r\n
. This combination marks the end of a line in text files (e.g.,.txt
files). - Unix/Linux: In Unix-based systems (such as Linux), only Line Feed (LF) is used to indicate the end of a line (
\n
). - Mac OS (pre-OS X): Older versions of macOS (before OS X) used Carriage Return (CR) alone to represent the end of a line (
\r
), though this has since been standardized to the Unix convention of LF (\n
).
- Windows: In Windows operating systems, line breaks are typically represented by the combination of Carriage Return (CR) and Line Feed (LF), written as
-
Common Applications:
- Text Files: Different operating systems use different conventions for line breaks, as mentioned above. When moving files between systems, improper handling of line breaks can lead to formatting issues.
- Network Protocols: CR is used in certain network protocols, such as HTTP, where it is part of the sequence
\r\n
(CRLF) to denote the end of headers or lines of data. - Programming: In programming languages like C, C++, and Python,
\r
can be used in strings to return the cursor to the beginning of the line, which is useful for overwriting text on the same line in a console or terminal.
-
Example:
- A string with a Carriage Return character could look like this in Python:
This would print "World" because the cursor moves back to the start of the line after "Hello" and overwrites it with "World".
- A string with a Carriage Return character could look like this in Python:
Carriage Return in Modern Systems:
In modern contexts, especially in web development and text processing, CR (Carriage Return) is often paired with LF (Line Feed) to create the CRLF sequence. This is commonly seen in protocols like HTTP, where headers are terminated with a \r\n
(Carriage Return + Line Feed) sequence.