3

The following code compiles

#include <cmath>
#include <iostream>

int main()
{
    std::cout << sqrt(4) << std::endl;
}

while this one does not, because cout is missing the std::

#include <cmath>
#include <iostream>

int main()
{
    cout << sqrt(4) << std::endl;
}

why does cout need the std and sqrt does not (even when sqrt is also std::sqrt)?

  • 3
    To answer the question in the title: always. Don't rely on it being required or not unless you saw a `using` directive. As for the example `cmath` is a c standard library header interface for C++. And it may inject the names into the global namespace, as well as to `std`. – StoryTeller - Unslander Monica May 21 '17 at 09:44
  • 1
    look http://stackoverflow.com/questions/11085916/why-are-some-functions-in-cmath-not-in-the-std-namespace – JFMR May 21 '17 at 09:45
  • http://stackoverflow.com/questions/11892976/why-is-my-log-in-the-std-namespace – M.M May 21 '17 at 09:49
  • @StoryTeller I think you should add that as an answer. Neither of the two linked duplicates answer this particular question directly. They're closely related, sure, but not exact duplicates. – John H May 21 '17 at 10:01
  • @JohnH - The thing is, I'm pretty certain there's a duplicate for every separate aspect of the question. Most of it is answered by the provided dups. And the missing dups can be edited in later by C++ gold badge holders. – StoryTeller - Unslander Monica May 21 '17 at 10:03
  • @StoryTeller That's true enough, and fair enough, too. – John H May 21 '17 at 10:05

0 Answers0