From what I understand, one of the reasons the C++ versions of C libraries like stdlib.h
(cstdlib
) were introduced was so that the global namespace is not polluted.
But it turns out that I am able to use malloc
in the global namespace even though I did not #include <stdlib.h>
.
So then why should I #include <cstdlib>
and then use std::malloc
?
(I'm using g++ version 4.8.2)
There used to be a requirement that the C headers (*.h
) only put names into the global namespace and that the corresponding C++ headers only put names into std
. That turned out to be impractical, and was often not followed. So the standards committee standardized existing practice, and changed the rule so that the C headers must put names into the global namespace and may put them into std
, and that the C++ headers must put names into std
and may put them into the global namespace.
The reason that the old rule was impractical is simply that it would require duplicating all of the C header content inside namespace std
, with a corresponding burden in maintenance of having two sets of code to update. Add to that the fact that in some cases the C headers are handled by a completely separate development team. The cost of this approach is prohibitive.
To answer the final question, either use #include <stdlib.h>
and malloc
or use #include <cstdlib>
and std::malloc
.
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