Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std:: is not needed when using ispunct() in C++?

Tags:

c++

std

#include <iostream>
#include <string>
#include <cctype>

using std::string;
using std::cin;
using std::cout; using std::endl;

int main()
{
    string s("Hello World!!!");
    decltype(s.size()) punct_cnt = 0;
    for (auto c : s)
        if (ispunct(c))
            ++punct_cnt;
    cout << punct_cnt
         << " punctuation characters in " << s << endl;
}

It seems that I can use ispunct() without std:: or declaring using std::ispunct; but I can't do that with std::cout or std::cin. Why is this happening?

like image 306
xiadaomike Avatar asked Aug 04 '13 20:08

xiadaomike


1 Answers

It means ispunct is part of the global namespace, rather than the std namespace. This is probably because ispunct is one of the functions brought over from C (hence it is in cctype).

On the other hand, cout and cin are part of the std namespace, not the global namespace.

Edit:

As to why things from C are in the global namespace instead of in the std namespace, I believe it has to do with allowing C code to compile by a C++ compiler with minimal changes, since C++ aims to be compatible with C.

According to the comments, ispunct is allowed, but not required, to be in the global namespace (but is required to be in the std namespace), in <cctype>. However, if you had included <ctype.h> instead, ispunct would be required to be in the global namespace.

like image 107
maditya Avatar answered Oct 13 '22 22:10

maditya