Why does the Endl exist in C++ and n already performs the same procedure?

Asked

Viewed 138 times

4

I’m sorry if the question seems trivial, but I don’t understand why Endl in C++, since n already performs the same task. It wouldn’t be "reinventing the wheel"?

  • 1

    Pq " n" is the line break qdo your output stream is std::cout, but when the output stream is from a file, "n" may be incompatible. That’s why they created std::endl, to have a unified interface.

3 answers

6

std::endl;

force a flush on the way out. cout is not the only possible way out of streams and in many cases it may be important to ensure flush() at the same time to be sure that the data was recorded or transmitted before continuing. It can be an LED panel for example and a endl; will probably instruct the driver to display the message at the same time. A "\n" can just put the data there and be waiting for the flush(). The panel can be multi-line for example. Or it can be a transmission buffer waiting for signal to transmit a message that can have many "\n". And endl; is easier to type :)

But in the case of cout and cerr is unnecessary and can be expensive in terms of performance. But this probably has zero importance because programs that write in cout are by definition very slow: great chance to be interactive programs. Note that C++ programs in general do not write in cout or cerr after all, except for tests and student programs. And cerr is the stream error pattern so the performance is little important, after all already gave error even. C++ programs usually talk to other programs and complex structures.

Anyway it’s in the Bible of recommendations for use, C++ Core Guidelines: inserir a descrição da imagem aqui The suggestion is to avoid and the conclusion there is that deep down it is seldom important and ends up being an aesthetic choice. And at the time of typing " in general needs shift and '\' can be in strange places on the keyboard, while endl; is in a much more favorable position. On western keyboards endl; is much faster :) On the international keyboard l and ; are adjacent and throughout qwerty keyboard e and d are side by side for example... And for example in ABNT quotes and backslash are at the edges of the keyboard. A P0$E after all.

2

the \n only takes up one space in the string to skip the line already the endl is an object that executes a \n, but also makes a flush in the buffer stdout

the endl is a better practice in the code, because it cleans the buffer together, but it uses more processing than the \n

2

The difference between both is the fact that Std::Endl forces the use Std::flush in the output operation, but may compromise performance.

Explicit difference:

std::cout << "\n" << std::flush

&

std::cout << std::endl

Browser other questions tagged

You are not signed in. Login or sign up in order to post.