3

I understand that rand(), as an example function from <cstdlib>, exists both in the global and the std namespace.

In effect the following will compile without errors, i.e. both calls to std::rand() and rand() will be legit.

#include <cstdlib>    
int main() {
    std::rand();
    rand();    
}

What is the use for this and how exactly is it implemented (the function being in both namespaces)?

gevang
  • 4,994
  • 25
  • 33
  • `std::rand` is a part of the C++ standard library while `rand` is for ANSI C compatibility. – T.Z Feb 23 '13 at 05:37

2 Answers2

6

The behavior is Uspecified behavior as per standard.
As per the standard including cstdlib imports the symbol names in std namespace and possibly in Global namespace. If you rely on symbol names being included in global namespace then your program is non portable and you are relying on behavior of a specific implementation.


To not rely on the implementatio behavior you must:

Include cstdlib and use fully qualified name for rand.

std::rand()

References:

C++11 Standard: D.5 C standard library headers
Para 3:

[ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. —end example ]


Good Read:
Should I include <xxxx.h> or <cxxxx> in C++ programs?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 3
    It's not implementation defined; it's unspecified. The difference is that implementation defined means that the implementation is required to document what it does. – Pete Becker Feb 23 '13 at 13:24
  • thanks for clarifying. unspecified behaviour answers the "when" though (i.e., when will the above code will compile). Any idea on how they are provided in both namespaces, when this might be the case, i.e. through the same implementation? – gevang Feb 23 '13 at 18:31
2

The reason is that it's originally a C function. It comes from C.

C++ re-implemented C functions like these into a std namespace. There is no difference that I know of, but it is recommended that C++ programmers use the function in the std:: namespace, first including the "c"whatever header (which is what you have indeed done with the "cstdlib" header).

(Plain C programmers would include the "stdlib.h" header, by the way.)

user2015453
  • 4,844
  • 5
  • 25
  • 27
  • with respect to the source of the functions in cstdlib, yes. However this does not answer the purpose/details of the dual namespace cast. Standard practise for c++ implementation-independent behaviour is std::rand(), as you also point out. – gevang Feb 23 '13 at 18:34