+ 1
What is the significance of 'using namespace', i mean why is it necessary to write that, what it does, and why we see an error while not using it ?
4 ответов
+ 3
Writing that means you are telling the compiler that you will use names from the standard library like cout, cin, etc. in your program so that you won't need to mention their library before using them later.
In other words, if you you write that line you can just write "cout," but if you don't write it, you should write cout like this:
std::cout
+ 3
Murtaza it's right.. it's a name resolution thing..
When you include 'iostream' you just tell the compiler that the functions in the iostream header are available in your code (i.e. cout).. but in order to access them you need to call them explicitly using the scope resolution command (std::cout just tells the compiler to execute the cout command whitch has the code in the standard library)... if you try to call any function in the iostream header directly like cout, the compiler will look for it in your own code, not in your header file and generate the error..
That's why namespaces exist... in a namespace you can specify all the explicit fuctions and variable names that you want to use directly (without the scope resolution command) inside your code.. In the std namespace, all the standard library functions and variables are explicit declared... when you write 'using namespace std' in your code, you're just bringing in your code all the explicit names specified in the std namespace, so you can call directly all those function instead of explicitly, like cout instead of std::cout
Hope it helped... sorry if it was to long...
0
But once when we inform the compiler to include 'iostream', doesnt it simply means that we'll using the function defined in that library. We know a function can be called only by the keyword by which it is defined(like in iostream printing lines can only be done by using 'cout'). Then why do we also need to tell the we'll be using names from std library as well ??
0
Have a look at this. I had same doubt. http://www.cplusplus.com/doc/tutorial/namespaces/