What is the difference between \\r, \\n, \\t, and \\f in C programming?

Β· 311 words Β· 2 minute read

These aren’t unique to “C programming”.

These are various “control characters”, originally used to control the write-head and paper feeder on Teletype machines.

\n is “line feed”. This would bump up the paper one line, whatever that was, but not move the write head.

If you did abc\ndef, the teletype would print

abc 
   def 

\r is “carriage return”. This would cause the write head to return to its leftmost position.

If you did abc\rdef, the teletype would print abc, and then would move the write head back, and then print def “on top of” your abc characters.

It’s worth mentioning that \r\n was needed to both advance the line and reset the write-head to the start of the next line. Unix and Linux’s screen TTY drivers use \n to do both, so this is a rare instance where I’m actually kinda on Microsoft’s side, as Microsoft’s display drivers did obey the old teletype standards and implemented the “correct” (if occasionally annoying) behavior.

\t is a tab character. This would advance the write head to the next “tab stop”, which tended to be defined by the teletype itself, but was usually the next character position divisible by 8. So, abc\tdef would look like

abc     def 

and abc\tdef\n\rghij\tklm

would print as

abc     def 
ghij    klm 

So, you used tabs if you wanted nicely-formatted columns of data.

\f is a “form feed”. It would tell the teletype that you’re done with the current page, so the entire page would scroll up to the “page break”, whatever that meant, and the write head would be set to the initial character at the top of the new page. If you loaded the paper carefully into the teletype, a form feed would advance past the perforated edge of the current “page” and to the next “page”.

The original answer to the question is by Greg Kemnitz .

Share:
waffarx cash back