using namespace std and library - c++

Why we need both the "header file" and the using namespace tag for the any library function to get executed properly. For example cout will not work unless we use iostream. Also it will not work unless we use "using namespace std". My question is why do we need combination of both using namespace std as well as #include <iostream> for cout to execute successfully?

Including a library header makes the library feature visible to your program code. Without that, your program has no idea that the library even exists. This is the part that is necessary.
Writing using namespace std simply allows you to write cout rather than the full name which is std::cout. It's a convenience, that's all.

cout is defined in the std namespace, and you can use it without adding a using namespace like
std::cout << "Hello, World" << std::endl;

Thanks for the reply. But my question is why do we need it in the first place.
Since once we exposed "iostream" then why can't we simply use cout.
Why to use std::cout or using namespace std?
When you don't use the std namespace, compiler will try to call cout or cin as if it weren't defined in a namespace. Since it doesn't exist there, compiler tries to call something that doesn't exist! Hence, an error occurs.

Related

What's the relation between libraries and namespaces?

Just started collage and I'm new in the world of programming. So, as I was learning C++ I bumped into a question that wouldn't let me be : "Why do i need to include "using namespace std" in my code to be able to write or read if i already got iostream?" , because I've been told that "cin/cout" are already defind in iostream library, but I noticed that if I write one of these lines alone it will give a compilation error. And ,therefore, what's the relation between iostream and "std" namespace ...Can someone explain , please? Thank you! <3
#include vs using
In simple terms:
#include <iostream> // include the header
int main() {
// now you can use stuff declared in that header
std::cout << "Hello world" << std::endl;
// if you are lazy you can "use" things:
using std::cout;
using std::endl;
cout << "Hello World" << endl;
}
You do not have to write using namespace std;! The cases where it is appropriate to do that are so rare and the cases where it really does great harm are so frequent that as a rule of thumb you can remember: Never use it! For details see here: Why is “using namespace std;” considered bad practice?. It is imporant to realize that the difference between fully qualifying a name, std::cout, and not fully qualifying the name, cout, is not just about typing 5 characters more or less (read on...).
libraries vs namespaces
What's the relation between libraries and namespaces?
The standard library puts everything in the std namespace. Namespaces help to keep things separated. A different library can contain a other_namespace::vector and there will be no confusion with std::vector because we have namespaces.
the really cool stuff
One deeper reason to use namespaces is Argument Dependent Lookup. I will try to explain with a simple example. Suppose you are using a library with some function template that does something with objects of a type you will have to supply:
namespace library {
template<typename T>
void do_something(T& a,T& b){
std::cout << "wrong...\n";
std::swap(a,b); // (1)
std::cout << "correct\n";
using std::swap;
swap(a,b); // (2)
}
}
I takes two objects and swaps them twice. You have to bear with me for second to understand why (1) is wrong and only (2) is correct. For now we have a library function template and to use that we need some type T:
namespace A {
struct foo{};
void swap(foo& a,foo& b) {
std::cout << "A::swap" << "\n";
}
}
Imagine foo is such that we know a better way than std::swap to swap to instances. Actually foo is empty, so to swap two objects we have to do nothing.
Lets recap: There is std::swap that comes with the standard library. Someone wrote a library (called library) we want to use. We want the library code to call A::swap instead of std::swap. The library author doesn't even know that A::swap exists.
Together with above A and library, this code
int main() {
A::foo a,b;
library::do_something(a,b);
}
will print:
wrong...
correct
A::swap
Live Example. What happened? This line:
std::swap(a,b); // (1)
calls std::swap, no doubt. Not what we want. We would like the library code to call our A::swap.
Now this:
using std::swap;
swap(a,b); // (2)
The first line pulls the name swap from std into the scope of the function. In the second line finally ADL kicks in because it says swap not std::swap. ADL in a nutshell is: a and b are from namespace A, so when the compiler searches for all possible swaps it also searches in A. If it finds one in A then it calls that (and if it does not find one in A there is still the swap coming from std). Hence only (2) calls our custom swap.
This can only work with namespaces. The "cool stuff" is that the library author does not need to know anything about your namespace but still their library code will call your function from your namespace if it exists.
I should note that not all code is generic library code. Often you want to write code where you know what happens in each detail, you want to know what functions get called. Often you do not want your code behave differently depending on a specific header being included or not. Hence, lots of code is better off with fully qualifiying function calls: std::foo.
conclusion
I hope that I could convince you that namespaces is not just about typing some characters more or less. using namespace std; for lazyness completly misses the point of namespaces. On the other hand, pulling names into scope via using std::foo; foo(); is
completely fine and enables ADL.
Libraries and namespaces are related by convention.
By convention, the symbols that a library provides to the programmer-user are contained in a namespace. This organizes things, and there are some higher level language features (ADL) that mean code in a namespace behaves differently than code outside of it.
When you type using namespace std; you tell the compiler "when you run into a symbol, also look into std to find if you can determine what it is". It is generally a really really bad idea to do this at "file" scope; doing it within a single short function is usable, but any more than that can lead to really tricky bugs.
The standard, professional way to interact with namespace std is to prefix your symbols with the namespace:
std::cout << "Hello world\n";
rather than
using namespace std;
cout << "Hello world\n";
and definitely never:
using namespace std;
int main() {
cout << "Hello world\n";
}
you can also grab single symbols, which isn't as bad as importing an entire namespace:
using std::cout;
cout << "Hello world\n";
but should also be avoided at "file" scope.
#include <iostream>
this includes the header file named iostream from the system search path. iostream is part of the standard library. By convention (and the C++ standard), the symbols that iostream provides your program with are located within namespace std.
By putting symbols in a namespace, you avoid conflict with your code. There are many, many symbols in std, and if #include <iostream> shoved some unknown number of symbols into your global namespace, you could easily get errors or the wrong function called in unexpected ways.
std::cout and using namespace std; cout and using std::cout are all ways to tell the compiler in what namespace to find the symbol cout.
#include <iostream> includes cout in namespace std; without it, your code is unaware of its existence.
C++ developed from C, and C has a textual inclusion model. #include actually takes the content of the file iostream and copy/pastes it into your file. Your compiler then reads that extended file and finds the symbols in <iostream>.
Because this textual inclusion could shove a LOT of stuff, having it isolated to a namespace prevents problems for you, the programmer.
Recently, C++ has added modules. Modules are an alternative to #include directives, in that it directly grabs symbols from a library and injects it into your code without a huge copy paste.
In modules, namespaces are still not directly connected to the module. You can
import std;
or
import std.iostream;
and that will just import the std library symbols, still in namespace std, into your code. (the C++ standard added modules, but did not modularize the std library yet, so those names above are speculation).
The symbol lookup is not directly connected to the symbol import.
This lets symbol import be done in large chunks, while lookup be done more carefully.
iostream is a library. It's code someone has written for you so you don't have to do it. By adding #include <iostream> you tell the preprocessor to paste in that code. But the functions and structures that are provided by this code might have names that interfere with others. But that isn't a problem because you can just separate them by putting them in a namespace, the STL(which upstream is part of) does this with std(short for standard, pronounced as 'stood'). When something is in a namespace, you must name that namespace to access stuff in that. i.e. std::cout. But sometimes you don't want to have to write std:: every time you want to access something from the STL. That's what using namespace std does for you. That way, you can just type cout. But this is a very bad idea!
Libraries
Libraries have portions of codes pre-written to provide you with functionalities. Could be in the form of functions/overloaded operators etc.
There are two types of libraries:
Standard Libraries e.g. #include <iostream> and the name of library is in angle brackets.
User defined/made e.g. #include "randomLib.h" and the name of library is in double quotes.
Namespaces
When you require multiple libraries for your project. There is possibility that the both may include multiple methods (function definition) with the same name or a single library may use same function names but in different namespaces. Namespaces are there to remove the confusion or ambiguity for the compiler and user.
Lets say lib 1 has namespace abc{ foo(); } and lib 2 has namespace def{ foo(); }
So you will do abc::foo() or def::foo() for you required functionality. Here abc/def is the namespace, :: is called scope resolution operator and foo() is the method you are calling.

Question regarding 'using namespace std'?

Recently i've noticed that if I don't include the 'using namespace std' in my program and just use 'std::cout' or 'std::endl' then my program still compiles just fine? Therefore if I use the 'std::' prefix is it even necessary to include the 'using namespace std'? Does the 'std::' prefix call the using namespace std? If someone can clear this up for me it would be greatly appreciated.
In C++, :: is called the "scope resolution operator", so std::cout means "The variable cout, which can be found inside std".
The using namespace std; directive means "For any name you can't find, also try looking it up in std". Thus, if you explicitly say std::cout (and equivalent for everything else in the std namespace), then you don't need using namespace std.
As others have said, it's usually considered bad style to use using namespace std;, because a lot of the names in std are things you might want to use elsewhere, for example std::count. A compromise option is to instead say using std::cout;, which will tell the compiler to look for cout in std but not anything else.
There's debate about whether to say using std::cout or just write std::cout everywhere you need it in your main C++ file, but most people believe that you should rarely if ever use using namespace. If you're writing a header file, though, you should never use a using directive at the top level because then every file which includes yours will get it, and they might want to use different names.
When you use:
using namespace std;
You're telling the program that anything that it can't find should be in the namespace std. For larger programs, this is a problem because you might be using multiple namespaces with functions that have the same name, so it's best to use std::cout for larger programs.

How does STD work?

I just started C++ and started doing basic text to console programs. In the book that I'm reading (Which is pretty old, I think) it uses cout to write stuff to the screen. Simple enough, right? But when I try to write cout it says that it's not defined. I searched around the internet and it said that I need std::cout or using namespace std; How does this stuff work? Explain it to me like you would to a 5 year old. I'm next level stupid.
std is the namespace which contains all functions and classes of the standard library. namespaces are used to avoid clashes of functions/classes with the same name. You can define a namespace northern_guy which contains a class cout.
std::cout << "output"; //prints to standard output
northern_guy:cout << "output"; //does what ever is defined in that namespace
(For this example you need to overload the << operator)
So you can use both functions/classes alongside in your code. That's why you should not use using namespace std;

Do I need to use the 'using namespace std' command?

I read in the C++ book -> C++ Programming: Visual Quickstart Guide that in order to use statements such as cin and cout without std:: you need to add the line using namespace std.
However at the moment I'm currently doing A-level computer science, using C++ and CBuilder, and I don't have to add that line to my program - since I'm able to use cout and cin in their own without running into any errors.
Is it not actually needed then? Or does Cbuilder configure std itself?
In short: Why am I able to skip using std despite having not declared that I'm not using it?
Some compilers/libraries are just more lax with respect to the Standard than others: according to the Standard, your program should not compile. Namespace pollution (putting names into a namespace they don't belong, in this case the global namespace) happens a lot, and leads to these and similar errors when you switch to another compiler and/or standard library.
Unless CBuilder has an option to add an implicit using namespace std; to everything it compiles (which would be horrible), the above is all anyone can tell you. There is no "configuring" happening anywhere, not sure what you might mean by that.
No, you don't need that using statement. It is an alternative to explicit namespace reference inline within your code. For instance, you can use
std::cout << "Hello world" << std::endl;
without having a using statement.
Or, you could include the using namespace std statement and then code:
cout << "Hello world" << endl;
It's a choice. Personally I prefer to omit the using statement and explicitly insert std:: where appropriate.
It depends on the compiler you use. Some compilers add it for you. But for your own goood and of course knowledge, add using namespace std; or you have to put std:: .

Why std::cout instead of simply cout?

I get these error messages for all cout and endl:
main.cc:17:5: error: ‘cout’ was not declared in this scope
main.cc:17:5: note: suggested alternative:
/usr/include/c++/4.6/iostream:62:18: note: ‘std::cout’
After following the suggestion, everything is fine. Now I am curious, why I had to do that. We used C++ in classes before, but I never had to write a std:: before any of those commands. What might be different on this system?
It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:
#include <iostream.h>
or
#include <iostream>
The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding
using std::cout;
or
using namespace std;
Just one idea, anyway.
In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put
using namespace std;
in your code in order to get at it.
However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.
Everything in the Standard Template/Iostream Library resides in namespace std. You've probably used:
using namespace std;
In your classes, and that's why it worked.
You could use the namespace
http://www.daniweb.com/software-development/cpp/threads/109029/what-its-the-use-of-using-namespace-std
But you might offend someone
Why is "using namespace std" considered bad practice?
You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.
"std" is a namespace used for STL (Standard Template Library). Please refer to https://en.wikipedia.org/wiki/Namespace#Use_in_common_languages
You can either write using namespace std; before using any stl functions, variables or just insert std:: before them.
If you are working in ROOT, you do not even have to write #include<iostream> and using namespace std; simply start from int filename().
This will solve the issue.