From someone who PMed me this question.
Hello,
I noticed in a lot of posts people have code such as:
1 2 3
|
std::pow
std::srand
std::time
|
I'm a little confused about a few things:
- Does the C++ standard require that all C methods have equivalent C++ methods that are in the std namespace?
- If these are C++ equivalents, then why aren't they placed in their own headers instead of headers that contain functions from C
1 2 3 4 5
|
e.g.
#include <math>
std::pow
#include <cmath> //or <math.h>
::pow
|
- Are these C++ methods in the std namespace very different from the C equivalents as far as how the standard defines their implementations?
- Is it good form to always stick to the methods from the std namespace, or is it a matter of preference to use the version from C or C++? |
Answers, in order:
- No. Standard C++ requires all
standard C functions exist in the
std namespace. Non-standard functions may or may not be placed in the
std namespace, depending on the compiler writer and the libraries you are using. Also, the standard functions may also be accessible in the global namespace (though they shouldn't be if you #include a standard C++ header).
- It's how they decided to do it. Remember, C++ has to be able to compile (most) standard C programs, so the choice of header name makes a difference in how the C functions are prototyped and linked. When compiling C++, choose the
<cfoo> headers for C standard library functions.
- They are usually the exact same function in the standard C library (libc).
- Since they are the same, it doesn't matter. But to extrapolate a little more in what I think you are really asking: "do I use the functions the C or std::C++ way?
When using C,
#include <foo.h>
.
When using C++,
#include <cfoo>
.
You then have a choice of how to manage the standard namespace. You can
1 2 3 4
|
#include <cfoo>
using namespace std;
...
foo();
|
The
using clause at the top of your module dumps all the stuff in
std into the current namespace.
If you are concerned about that "namespace pollution", then you can ask for only specific items to be placed in the current namespace with, for example,
1 2 3 4
|
#include <cfoo>
using std::foo;
...
foo();
|
If you want to avoid any possible name conflicts, then spell out an object's full name each time you use it.
1 2 3
|
#include <cfoo>
...
std::foo();
|
Hope this helps.