What is the difference between endl and \n in C++?
Both endl and ‘\n’ give the same result. They both work as the enter key. The difference between the two lies in the mechanism of their working.
To understand the difference in their working lets first understand some basic concepts about input and output in C++.
In C++ input and output are performed as a sequence of bytes more commonly known as ‘streams’. The direction of flow of the stream decides if its an input stream or an output stream.
If the flow is from a device(keyboard, webcam, mouse) to main memory then it is input stream and if its from the main memory to a device(speaker, display) then it is called an output stream.
Every time we use ‘cout’, the data needed to be displayed is stored in the output stream. Whenever our program encounters a reading operation (cin), it flushes the output stream and the messages are displayed on the screen.
Now, coming back to the question, the difference lies in the working of the two to achieve the result.
endl flushes the output screen every time it is encountered while on the other hand ‘\n’ is just a character that inserts a new line. Due to the frequent flushing of ostream(output stream) endl is slow as compared to the ‘\n’ character.
Some other differences:
- Endl is a manipulator and doesn’t occupy any memory in the ostream while \n is a character and occupies 1 byte in memory
- Endl is supported only in C++ while both C and C++ support the ‘\n’.