Department of Engineering

IT Services

Scope and Namespaces

scope is the part of the program where a name has a meaning. The more localised variables are the better. There's

  • file scope - entities can be made visible only to entities in the same file.
  • function scope - entities can be made visible only to the function they're created in.
  • block scope - delimited by '{' and '}'.
  • class scope - entities can be made visible only to the class they're created in.
  • namespaces - A namespace is like a class that has no functionality. Stroustrup uses them a lot. You can put an entity into a namespace by doing something like

    namespace test {
     int i;
    }
    

    then using test::i to access the variable. The command ``using namespace test'' will make all the entities in the namespace available for the rest of the unit that the statement is in, without the ``test::'' being necessary. The standard library names are in the std namespace. It's tempting to put ``using namespace std'' at the top of each file to access all the standard routines, but this ``pollutes the global namespace'' with many routine names you'll never use, so consider using more specific commands like ``using std:string''

It's possible for a local variable to mask a global variable of the same name. If, in a function that has a local variable i you want to access a global variable i, you can use ::i, but it's better to avoid such nameclashes in the first place.