41

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(); } 
4
  • 3
    That's not the output I get (At least once I fix the void main(), and the nonstandard conio.h stuff.) Commented Jan 9, 2011 at 9:46
  • I'm using Visual C++ output is "hai" Commented Jan 9, 2011 at 9:48
  • if you put \n at the end of ab like 'ab\n' will get what you desire? Commented Jan 9, 2011 at 9:50
  • 4
    @Octopus: I don't think he desires any particular output, he wants to understand the cause of the output he is getting. It is obviously just 'puzzle code' and of no practical use. Commented Jan 9, 2011 at 10:01

3 Answers 3

83

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 
Sign up to request clarification or add additional context in comments.

1 Comment

@mr_eclair typo on the last line : fixed
15

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

Comments

6

Step-by-step:

[newline]ab

ab 

[backspace]si

asi 

[carriage-return]ha

hai 

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.