0

What is the difference between /n and endl in c++?

28th Sep 2020, 3:01 AM
Linus Tech Tips Fans
Linus Tech Tips Fans - avatar
3 Respuestas
+ 3
The difference is in performance. When we have to output something , first they need to be stored in an output buffer before writing it to output device. When we use endl it causes the buffer to flush the output stored in it while using \n doesn't cause it. Example, #include <iostream.h> int main(){ for (int i=1;i<=10;i++){ cout<<i<<endl; } return 0; } Here the output buffer is flushed each time the compiler execute cout<<i<<endl Where as in below example, #include <iostream.h> int main(){ for (int i=1;i<=10;i++){ cout<<i<<"\n"; } return 0; } Output is stored in buffer until all numbers are filled and buffer will be flushed at last only once. We can't visually see the difference for small programs but when executing large programs we may see the lag.
28th Sep 2020, 3:25 AM
Aravind
Aravind - avatar
+ 1
Seb TheS well endl is equivalent to calling \n in addition with flush() function to flush the buffer after newline .. there may be cases where we need flushing , so it is added to c++ even though it's not there in c. You can refer this https://stackoverflow.com/questions/7324843/why-use-endl-when-i-can-use-a-newline-character
28th Sep 2020, 4:57 AM
Aravind
Aravind - avatar
0
DAVINCI If endl isn't better than newline then why does it exist?
28th Sep 2020, 4:49 AM
Seb TheS
Seb TheS - avatar