Show Lecture.UsingNamespaceStd as a slide show.
CS253 Using Namespace Std
Namespaces
#include <iostream>
allows you to use
symbols such as cin
and cout
.
#include <iostream>
using namespace std;
int main() {
cout << 1/8.1;
return 0;
}
0.123457
Namespaces
- However, the full names of these symbols are really
std::cin
and std::cout
.
- That’s why we need
using namespace std;
#include <iostream>
int main() {
cout << 1/8.1;
return 0;
}
c.cc:4: error: 'cout' was not declared in this scope
Namespaces
- You could, if you wished, just use the full name.
- It’s not pretty.
#include <iostream>
int main() {
std::cout << 1/8.1;
return 0;
}
0.123457
How it works
- Library symbols (
cout
, endl
, exit
) go into
the std::
namespace.
- User symbols (
main
, global vars) go into the global namespace.
- No collisions! Library symbols don’t interfere with your symbols.
#include <iostream>
constexpr auto pi = 3.14159;
void cout() {
std::cout << "π=" << ::pi << std::endl;
}
int main() {
::cout();
return 0;
}
π=3.14159