<iostream.h> is deprecated and may not work in modern compilers.
<iostream> is standard and will work in all modern compilers.
Namespaces (like the std namespace) are used to avoid name conflicts. When everything is declared in the global namespace, it gets "polluted" and makes it easier to have clashes with other things of the same name.
For example... consider the following:
1 2 3 4 5 6 7 8 9 10
|
void swap(int& a,int& b)
{
// do stuff here
}
int main()
{
int a, b;
swap(a,b);
}
|
This will compile fine. But let's say that later, my program changes and I need to use something in the <algorithm> header, so I do this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <algorithm>
using namespace std;
void swap(int& a,int& b)
{
// do stuff here
}
int main()
{
int a, b;
swap(a,b);
}
|
Now I get errors because my swap() function conflicts with the swap() function declared in the <algorithm> header.
By keeping the standard lib in the std namespace, it separates its functions/vars from your program's vars.
So instead, we can do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <algorithm>
//using namespace std; <- don't do this
void swap(int& a,int& b)
{
// do stuff here
}
int main()
{
int a, b;
swap(a,b); // calls my swap function
std::swap(a,b); // calls <algorithm>'s swap function
}
|
The "using namespace std;" shortcuts the
std::
prefix which may seem convenient, but it ultimately defeats the entire point of namespaces and introduces a lot of pollution into the global namespace, opening up lots of opportunity for name conflicts. It's best to avoid it in larger projects.