13

I wrote the following program in the C and when I run it, I was surprised by looking at the output.

Here is the program

int main()
{    
       printf("\nab");
       printf("\bsi");    
       printf("\rha");    
}

The output is :- hai whereas I was expecting "absiha" since \n is for new line, \b is for backspace(non erase) and \r is for carriage return. So I was expecting that curson would be at "i" character because \r has been applied but when I run it and saw the output I was totally surprised and confused. Can anyone please explain me the output?

1
  • It could be operating system specific. Commented Feb 15, 2018 at 13:51

2 Answers 2

27

Let's take it one step at a time:

<new line>ab<backspace>si<carriage return>ha

First, handle the backspace. Note that even though it is "non-erase", the next character to be output would overwrite what was backspaced over:

<new line>asi<carriage return>ha

Now, a carriage return means to go back to the beginning of the line. So the "ha" overwrites the "as" in "asi:

<new line>hai

Now, the cursor is currently sitting on the i, so the next character to be output would overwrite i.

Sign up to request clarification or add additional context in comments.

2 Comments

you mean backspace would just move cursor one position before? just like an insert statement ?
@ankur.trapasiya I'm half-guessing that's what you meant by "non-erase", but I've seen it before in other contexts - like, if I have terminal output in a long running program, then hit backspace on the keyboard, the cursor moves over but the character itself stays there until new output is put on top of it. No clue what you mean by "like an insert statement".
13

Visit http://en.wikipedia.org/wiki/Escape_sequences_in_C

Escape Sequence Character \a Bell (speaker beeps) \b Backspace (non-erase) \f Form feed/clear screen \n New line \r Carriage Return \t Tab \v Vertical tab \\ Backslash \? Question mark \' Single quote \" Double quote \xnn Hexadecimal character code nn \onn Octal character code nn \nn Octal character code nn

1 Comment

thanks for informative answer. Probably you should read the question first.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.