std::endl vs “\n”

As we know, these two lines seem to be equivalent. Indeed, if you write a hello world program and try to use both ways, you shall get the same result.

std::cout << "Hello world!" << std::endl;
std::cout << "Hello world!\n";

However, is std::endl and “\n” equivalent? No, they are not. The reason is that std::endl flushes the output buffer, while “\n” doesn’t.

That means that every time we use std::endl, the buffer should be flushed. In other words, every time you print something, the system should flush the buffer, which I think is not a must, thus I suggest using “\n”, when you just want to print something.

However, notice that I strongly suggest you to use std::endl when debugging. Especially when it comes to memory management, std::endl is a must (maybe not in all debugging messages, but I suggest to use it for certainty).

Page created by G. (George) Samaras (DIT)


2 thoughts on “std::endl vs “\n”

  1. Pingback: Now that I'm used to C++, printf() >>>>>> cout >> endl;

  2. Pingback: vectors and C++11

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s