The difference between \n and endl in C++

The difference between \n and endl in C++

- 1 min

About two years ago when I took my first C++ class, I remember my professor used both \n and endl to create new lines. Having been previously acquainted with \n from Python, I wondered what difference the two had on the running of a program. One day after class, I asked him what the difference was and he told me that endl also flushes the buffer.

I wanted to find out more about this, so when I got home I checked with the all-knowing StackOverflow for more information on the two and found out that endl is a stream manipulator that forces a flush the buffer which can have a negative impact on the performance of a program. This is in contrast to \n which is a typical escape sequence and only 1 byte (for '\n') or 2 bytes (for "\n") large. One interesting little nitpick is that using "\n" will cause the program to run just slightly slower than '\n' since "\n" is a string literal representing two characters, the '\n' newline character and the null terminator '\0'.

Therefore the wanton use of endl should be avoided in instances where performance is major issue.

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora