Endl vs \n in C++

About programming and getting involved with Linux Mint development
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
YellowSnowman
Level 1
Level 1
Posts: 1
Joined: Thu Oct 21, 2021 11:13 am

Endl vs \n in C++

Post by YellowSnowman »

Does my programme size decides whether I should use endl or \n?
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
rene
Level 20
Level 20
Posts: 12240
Joined: Sun Mar 27, 2016 6:58 pm

Re: Endl vs \n in C++

Post by rene »

Whatever that question in fact means, the answer's still "no" it seems. In C++ (and in other contexts than e.g. C-compatible printf() where \n is also specified to) endl is specified as inserting \n and flushing the stream.
FrostedCupcake
Level 1
Level 1
Posts: 1
Joined: Mon Oct 25, 2021 12:10 pm
Location: India

Re: Endl vs \n in C++

Post by FrostedCupcake »

In a small program there is not much of a difference between endl and \n in C++.
But, for large programs including multiple IO Operations, endl introduces extra overhead of flushing the buffer.
This leads to more CPU cycles being consumed and hence lower throughput. To understand more about the concept behind "the flushing the buffer" and "the how endl and \n works differently" I would suggest you to go through this article.
xanaki
Level 1
Level 1
Posts: 15
Joined: Fri Sep 17, 2021 8:40 am
Location: Finland
Contact:

Re: Endl vs \n in C++

Post by xanaki »

Just use "<< endl" with your stream outputs. It confirms to the standards.
Bring me a shrubbery, Shrubbery of Mint. Ni!
From Finland with love and liquor since 1972.
SimonPeter
Level 5
Level 5
Posts: 582
Joined: Tue Jul 13, 2021 5:13 am

Re: Endl vs \n in C++

Post by SimonPeter »

std::endl prints out a newline AND flushes the stream (ensures that everything in the buffer is written right now).
"\n" just prints a newline.

std::endl is slower than "\n" , but it ensures that the output appears instantly -- good for printing out debug info that should be printed within certain periods of time.
"\n" is faster , but the output may appear at a later time -- good for eg. printing out the output in competitive programming / programs that print a lot.
Locked

Return to “Programming & Development”