Does anyone know the difference between endl (cout) and cout << endl?

I thought it was the same thing, but when I sent the code to the online judge (with endl(cout) ), he gave me the verdict "Invalid answer", then I tried to send another using cout << endl , and the judge accepted the code! Does anyone know the difference between these teams?

+4
source share
4 answers

I don’t know what I know.

std::endl is a function that takes a stream and returns a stream:

 ostream& endl ( ostream& os ); 

When you apply it to std::cout , it will immediately apply this function.

On the other hand, std::basic_ostream has an operator<< overload with a signature:

 template <typename C, typename T> basic_ostream<C,T>& operator<<(basic_ostream<C,T>& (*pf)(basic_ostream<C,T>&)); 

which will also immediately apply this function.

So technically, there is no difference, although the stream std::cout << std::endl more idiomatic. Perhaps the judge-bot is simplified and does not understand this.

+3
source

The only difference is that endl(cout) considered as a global function, while in cout << endl , endl considered as a manipulator. But they have the same effect.

+2
source

There is no difference in behavior between the two forms. Both refer to the same endl function, which can be used as a manipulator ( cout << endl ) or as a free function ( endl(cout) ).

+1
source

The answers above are correct! Also, depending on whether you use << endl; or endl(cout) , this can reduce the number of lines in your code.

Example:

You might have something like:

cout << "Hello World" << endl;

OR

cout << "Hello World";

endl(cout);

HOWEVER, cout << "Hello World" << endl(cout); //Does not work

So in this example, this is 2 lines versus 1 line.

+1
source

Source: https://habr.com/ru/post/1399660/


All Articles