Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the diffrence between std::cout<< x ; and std::cout<<x<<std::endl;?

Tags:

c++

I'm a newbie to programming, I started teaching myself yesterday, I've been getting everything but I honestly, do not understand the difference between

std::cout << x;

and

std::cout << x << std::endl;

Nobody has explained this to me, and I'm asking to stay on the safe side.

like image 864
ssleepie Avatar asked Dec 14 '22 07:12

ssleepie


1 Answers

endl writes a new-line to the stream, so subsequent output will appear on the next line. It also flushes the stream's buffer, usually causing a slow-down.

This flushing means that 99% of the time, endl is a mistake, and you should just write "\n" (or '\n') instead. When you really do want to flush the stream, I think it's better to make that explicit by invoking std::flush instead:

std::cout << x << '\n' << std::flush;

As far as run-time actions goes, this is equivalent to using std::endl, but in terms of making your intent clear, it's drastically superior.

like image 116
Jerry Coffin Avatar answered Feb 23 '23 07:02

Jerry Coffin