my compiler adds this automatically:
using namespace std;
what is it and what does it do ?
Printable View
my compiler adds this automatically:
using namespace std;
what is it and what does it do ?
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
This allows you to avoid conflicts of global variables (very useful when you work on a team).Code:namespace myspace
{
int i;
float f;
}
i = 4; // doesn't work! wrong scope
myspace::i = 3; // does work, scope resolution operator
By convention, all functions/classes/variabels in the C++ runtime library are grouped together in the large namespace std.Code:namespace a
{
int somevar;
}
namespace b
{
int somevar;
}
somevar = 3; // which one?
a::somevar = 5; // this is unambigous
b::somevar = 9;
Because writing std::... every time may be annoying, there is the using keyword. You can use it to import certain identifiers or a whole namespace to global scope.
I hope that clears it up some.Code:#include <iostream>
using std::cout; // import cout to global scope
cout << "Hello"; // now possible
cout << endl; // not possible, endl is not imported
using namespace std; // import the whole std namespace to global scope
int i;
cin >> i;
cout << i << endl; // possible, all symbols imported
Just curious, what if declared a variable called "i" outside the namespace myspace? I hope it won't give you any error and will let you use that ouside i.Quote:
Originally posted by CornedBee
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
[code]
namespace myspace
{
int i;
float f;
}
you can still use it
if you had
you can access the global i likeCode:
int i;
void blah(){
int i;
}
Code:::i