4

I thought they were the same thing, but when I sent a code to an online judge (with endl(cout)) it gave me "Wrong answer" verdict, then I tried to send another with cout << endl and the judge accepted the code! Does anyone know the difference between those commands?

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
hinafu
  • 689
  • 2
  • 5
  • 13
  • If you have `using std::cout` then the first form will compile but the second won't (due to argument dependent lookup). I can't think of cases where the second form works but the first does not as is the case with the online judge. – interjay Mar 04 '12 at 16:05

4 Answers4

3

There is none that I know of.

std::endl is a function that take a stream and return a stream:

ostream& endl ( ostream& os );

When you apply it to std::cout, it just applies the function right away.

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

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

which will also apply the function right away.

So, technically, there is no difference, even though stream std::cout << std::endl is more idiomatic. It could be that the judge bot is simplistic though, and does not realizes it.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • I guess the only difference is that there are two function calls instead of one with `cout << endl`. – Seth Carnegie Mar 04 '12 at 16:01
  • Thanks a lot! in the future I will be using only cout << endl :) – hinafu Mar 04 '12 at 16:03
  • Wait, `endl` shouldn't convert to `ios_base& (*pf)(ios_base&)`, IIRC there is another overload. – Xeo Mar 04 '12 at 16:07
  • `endl` cannot be converted to a `ios_base& ( *pf )(ios_base&)` because its parameter and return type have to be a `basic_ostream` specialization. `basic_ostream` has a template member: `basic_ostream& operator<<(basic_ostream& (*pf)(basic_ostream&));`, though. ` – CB Bailey Mar 04 '12 at 16:14
2

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

talnicolas
  • 13,885
  • 7
  • 36
  • 56
1

Answers above are correct! Also, Depending whether you use << endl; or endl(cout) it could reduce the number of lines in your code.

Example:

You can have something like:

cout << "Hello World" << endl;

OR

cout << "Hello World";

endl(cout);

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

So it is 2 lines vs 1 line in this example.

Athena
  • 3,200
  • 3
  • 27
  • 35
Omid CompSCI
  • 1,861
  • 3
  • 17
  • 29
1

There is no difference in behaviour between those 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)).

John Bartholomew
  • 6,428
  • 1
  • 30
  • 39