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.
While this practice is okay for example code, pulling in the entire std namespace into the global namespace is not good as it defeats the purpose of namespaces and can lead to name collisions. This situation is called namespace pollution.
why is it compulsory to use using namespace std ? It isn't. In fact, I would recommend against it. However, if you do not write using namespace std , then you need to fully qualify the names you use from the standard library.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With