3

Case 1:

#include <iostream>
int main() 
{
   std::cout<<"Hello World"<<endl;
      return 0;
}

Compiler give an error because endl need namespace std like std::endl.

case 2:

#include <iostream>
int main() 
{
      endl(std::cout); 
      return 0;
}

But, In second case without namespace std, endl working fine. Demo.

Why does endl working fine without namespace std?

msc
  • 33,420
  • 29
  • 119
  • 214
  • 5
    ADL I guess..... – YSC May 25 '18 at 11:43
  • `endl` and `basic_ostream` (which is the type of `std::cout`) are both in `std`, so ADL kicks in. See https://stackoverflow.com/questions/8111677/what-is-argument-dependent-lookup-aka-adl-or-koenig-lookup?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Holt May 25 '18 at 11:44
  • 2
    http://en.cppreference.com/w/cpp/language/adl – stefaanv May 25 '18 at 11:45
  • @rsp do you agree on the duplicate? Does it answer your question? – YSC May 25 '18 at 11:45
  • 2
    @YSC I don't. Duplicates are for duplicate *questions* - this question is not a duplicate of that. (The *answer* is, but that's different). – Martin Bonner supports Monica May 25 '18 at 11:47
  • Before I had that badge I could simply vote to close a question as a duplicate. Sometimes, when on doubt, I'd like to get back to that instead of single handedly close the question. – YSC May 25 '18 at 11:52
  • @YSC: If you are in doubt, don't cast the vote. That applies whether you have a dupehammer or not. – Lightness Races in Orbit May 25 '18 at 11:59
  • In fact, ADL also explains why case 1 works, since the first `<<` refers to a `std::operator<<` function. – aschepler May 25 '18 at 11:59
  • @MartinBonner: FWIW SE prefers we consider "whether the question has been answered elsewhere" rather than whether the question is actually the same, though I'm not sure I agree with that and I definitely agree that the wording across the site doesn't support it. – Lightness Races in Orbit May 25 '18 at 12:00
  • @YSC : I have just [asked on meta](https://meta.stackoverflow.com/questions/368596/should-we-close-as-duplicate-for-answered-by-these-answers-or-only-for-same) whether this should have been closed as duplicated. I am rather expecting the answer "yes", although that is not my preference. – Martin Bonner supports Monica May 25 '18 at 12:28
  • @MartinBonner thx, will monitor – YSC May 25 '18 at 12:28
  • @LightnessRacesinOrbit see above for meta question – Martin Bonner supports Monica May 25 '18 at 12:30
  • 3
    Meta discussion is clear: it should be closed as a duplicate - but this is the one case where closing a question doesn't necessarily mean it was a bad question. – Martin Bonner supports Monica May 25 '18 at 12:47

0 Answers0