tags:

views:

122

answers:

2

Hi Guys,

when I'm reading some c++ sample code for beginner , I'm puzzled at the usage of toupper in the following line :

std::transform(data.begin(), data.end(), data.begin(), ::toupper);

from the above line, I know that "transform" is from namespace std , but I don't know which namespace does toupper come from . maybe there is a default namespace for c++ but that is just my guess. so could you explain the usage of toupper here to me ?

+8  A: 

If you include

<cctype>

then toupper() is in namespace std. If you include

<ctype.h>

then toupper() is in the global namespace. (The one everything ends up in if not defined in a specific namespace. The one you refer to with a leading :: when you're in a specific namespace.)

The same rule applies to <cstring> vs. <string.h>, <cstdlib> vs. <stdlib.h> etc.

DevSolar
+4  A: 

If you are puzzled from the ::toupper syntax, it is telling you that in this case, the function is in the global namespace. You can always prepend a double colon to a name and that will tell the compiler to check in the global namespace and not search from your inner namespace out.

void foo() { std::cout << "global"; }
namespace inner {
   void foo() { std::cout << "inner"; }
   void call() {
      foo();   // prints inner
      ::foo(); // prints global
      ::inner::foo(); // prints inner (fully qualified namespace)
   }
}
David Rodríguez - dribeas