Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carriage return in C?

Tags:

c

Output of Following program is : hai

I didn't get how the \r carriage return works in this program and in real can any one help me out ?

#include <stdio.h> #include<conio.h>  void main() {     printf("\nab");     printf("\bsi");     printf("\rha");     _getch(); } 
like image 484
Vishwanath Dalvi Avatar asked Jan 09 '11 09:01

Vishwanath Dalvi


People also ask

What is carriage return Value?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.

What is carriage return and form feed in C?

In short: Carriage return ( \r or 0xD ): To take control at starting on the same line. Line feed ( \n or 0xA ): To Take control at starting on the next line. Form feed ( \f or 0xC ): To take control at starting on the next page.

Is carriage return a character?

CR (character : \r, Unicode : U+000D, ASCII : 13, hex : 0x0d) : This is simply the 'r' character. This character is commonly known as 'Carriage Return'. As matter of fact, \r has also has a different meaning. In older printers, \r meant moving the print head back to the start of line and \n meant starting a new line.

What key is carriage return?

Enter key. Also called the "Return key," it is the keyboard key that is pressed to signal the computer to input the line of data or the command that has just been typed. The Enter key was originally the "Return key" on a typewriter, which caused the carriage to return to the beginning of the next line on the paper.


2 Answers

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai 
like image 50
icecrime Avatar answered Oct 01 '22 20:10

icecrime


Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

like image 43
0xHenry Avatar answered Oct 01 '22 20:10

0xHenry