Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of \b and \r in C

Tags:

c

\b and \r are rarely used in practice. I just found out that I misunderstood these two escape sequences. A simple test:

printf("foo\bbar\n"); 

I expected it to output fobar, because \b will backspace the cursor, and b will overwrite the second o, but instead it outputs: foobar

The same is with \r:

printf("foo\rbar\n"); 

I thought \r will move the cursor to the beginning of the current line, so bar will replace foo, so the final output should be bar. However, it actually outputs:

foo bar 
like image 592
Yu Hao Avatar asked Jun 21 '13 13:06

Yu Hao


People also ask

What is use of \r in C?

'\r' is the carriage return character.

What is \r in escape sequence?

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line. The cursor is the position where the next characters will be rendered. So, printing a \r allows to override the current line of the terminal emulator.


1 Answers

The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).

It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.

like image 100
ComicSansMS Avatar answered Sep 16 '22 15:09

ComicSansMS