7

This code is correct C++:

#include <ctime>
int main()
{
   std::time_t t = std::time(nullptr);
}

However, this compiles fine too (GCC 5.2):

#include <ctime>
int main()
{
   time_t t = time(nullptr);
}

More generally, it seems that legacy "C" data types and functions don't require namespace qualifying.

It seems to me that this is a dangerous behaviour, as both are accepted and the possibility of name collision is still there. I thought (erroneously ?) that the standard namespace std was there to protect me against this.

So my question is: why did the standardization committee allow such a behaviour in C++11 ? Am I wrong in my analysis ?

I understand the issues about legacy code, but I though the ".h" header files (iostream.h, ...) were there specifically to address this point.

Edit: the linked question is not a duplicate, it asks about if one should or not use the std:: version of legacy functions. What I want to know is the rationale behind this behaviour.

Community
  • 1
  • 1
kebs
  • 6,387
  • 4
  • 41
  • 70
  • `iostream.h` is not in fact a standard C++ header. – Igor Tandetnik Sep 22 '15 at 14:27
  • 2
    possible duplicate of [When using C headers in C++, should we use functions from std:: or the global namespace?](http://stackoverflow.com/questions/32606023/when-using-c-headers-in-c-should-we-use-functions-from-std-or-the-global-na) – alain Sep 22 '15 at 14:28
  • @Galik Could you elaborate ? ;-) – kebs Sep 22 '15 at 15:15
  • 2
    It turned out that on some systems, the C++ implementation just *have to* use the existing C functions. Perhaps because some of them *are* the system calls needed. So the C++11 standard just documented this "leak" between namespace std and the global namespace, as existing practice. It happened with C++98 as well, even though that standard didn't allow it. – Bo Persson Sep 22 '15 at 15:15
  • @Bo-Persson Nice comment, consider adding as answer. – kebs Sep 22 '15 at 20:11

1 Answers1

3

Since C++11, implementations are formally allowed to put C standard library names defined in <cxxx> headers in the global namespace. This doesn't mean that they are required to, so your second code sample may fail on a different platform.

So to say that std is not required for C identifiers is not entirely correct. It may not be required on some implementations, that is all.

Note that before C++11, many implementations did it anyway, although technically they weren't supposed to.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 2
    Doesn't really answer the question, just re-iterates what was asked. The question is "why" it is allowed, wha't the rationale. – SergeyA Sep 22 '15 at 14:46
  • @SergeyA Yeah, good point. I may delete this. I focused on the question title, which suggests the situation isn't properly understood by OP. – juanchopanza Sep 22 '15 at 14:47