Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "#include <iostream>" do?

Tags:

c++

As I started learning basic C++, I've always used the headings

#include <iostream> using namespace std; 

I want to question what is the point of iostream. Is it required every time as a heading?

like image 206
William Avatar asked Mar 25 '14 20:03

William


1 Answers

In order to read or write to the standard input/output streams you need to include it.

int main( int argc, char * argv[] ) {     std::cout << "Hello World!" << std::endl;     return 0; } 

That program will not compile unless you add #include <iostream>

The second line isn't necessary

using namespace std; 

What that does is tell the compiler that symbol names defined in the std namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example

#include <iostream> using namespace std; int main( int argc, char * argv[] ) {     cout << "Hello World!" << endl;     return 0; } 

Notice you no longer need to refer to the output stream with the fully qualified name std::cout and can use the shorter name cout.

I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:

#include <iostream> using std::cout; using std::endl;  int main( int argc, char * argv[] ) {     cout << "Hello World!" << endl;     return 0; } 

But that is a matter of personal preference.

like image 155
amdn Avatar answered Sep 28 '22 04:09

amdn