Introduction to Programming and C++

Contents Previous Topic Next Topic

Because names in C/C++ can be global, this leads very quickly to the possibility that, for example, two functions in two different files have the same name, leading to both interesting and difficult-to-find bugs.

A namespace is a prefix which may be used to give unique identifiers to a collection of variables, functions, and classes.

namespace silly_math {
	int pi = 3.14;
	int e =  2.718281828;
}

All the names within the silly_math namespace can be access/modified outside this namespace by using:

  • silly_math::pi, and
  • silly_math::e

For example,

#include <iostream>
using namespace std;

namespace silly_math {
	int pi = 3.14;
	int e =  2.718281828;
}

int main() {
	cout << "pi = " << silly_math::pi << endl;

	return 0;
}

In some cases, it might get frustrating to continuously use a name space, and hence, you can use the statement:

using namespace silly_math;

which allows you to access the variables by their shorter name. For example,

#include <iostream>
using namespace std;

namespace silly_math {
	int pi = 3.14;
	int e =  2.718281828;
}

using namespace silly_math;

int main() {
	cout << "pi = " << pi << endl;

	return 0;
}

C++ Standard Library

All C++ Standard Library packages are wrapped in the std namespace, and thus, to use any function, you must either use the std:: prefix or the using namespace std; statement. For example,

#include <iostream>
using namespace std;

int main() {
	cout << "Hello world" << endl;
	return 0;
}

or

#include <iostream>

int main() {
	std::cout << "Hello world" << std::endl;
	return 0;
}

Local Variables

Local variables bind closer than global names in a namespace and therefore combining using together with local variables with the same names can lead to difficult-to-understand code.


Contents Previous Topic Top Next Topic