using or not std::

hey, dudes, I saw a this code in my book, it doesn't declare using namespace std;
1
2
3
4
#include <locale>

isalnum(ch, std::locale());
std::tolower(ch, std::locale());


I'm wondering why
isalnum()
doesn't need prefix std::, while
tolower()
needs std::, why?
Is there something like judging something don't need std::, operation needs std:: ?
Everything in C++ headers is supposed to be in the std nanespace.
C++ headers are the ones not ending with an .h extension.

So even if your code happens to compile fine without prefixes, stick to the rules and add them.
> I'm wondering why isalnum() doesn't need prefix std::

It does. http://en.cppreference.com/w/cpp/string/byte/isalnum

In general, assume that every name in the standard library (except names of macros, operator new and operator delete) is defined within the namespace std.

It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations


Nevertheless, this code will always compile cleanly:
1
2
3
4
5
6
7
#include <locale>

int main()
{
    char c = tolower( 'A', std::locale() ) ; // std::tolower
    isalnum( c, std::locale() ) ; // std::isalnum
}

because of Koenig lookup http://en.wikipedia.org/wiki/Argument-dependent_name_lookup
I think that tolower also needs no prefix std::.

Usually C++ compilers place standard C names in the global namespace by using directive

using std::isalnum;
using std::tolower;

So though these functions defined with the second parameter of type std::locale are C++ functions

template <class charT> bool isalnum (charT c, const locale& loc);
template <class charT> charT tolower(charT c, const locale& loc);

their names coinside with standard C functions with one parameter.

int isalnum(int c);
int tolower(int c);

And the directives using place the whole family of functions with the same name in the global namespace.

But it is implementation defined whether the compiler will place standard C functions in the global namespace. So in any case it is better to use prefix std::.

Last edited on
Topic archived. No new replies allowed.