PDA

Click to See Complete Forum and Search --> : newbie question


nina2kool
Feb 22nd, 2001, 07:45 AM
Hi,

I am learning C++ and I am using VC++ 6.0. In some of the books I read, they will start a program with something like this:

#include <iostream.h>

using std::cout;
using std::cin;
using std::endl;

My question is that, what is the purpose of listing all the functions that you are going to use? Is it really necessary because my program still compile and run without all those "using" statements. Is it because VC has done that for me or something?

Thank you very much.

nina.

Vlatko
Feb 22nd, 2001, 08:12 AM
You could do it like this:

#include <iostream>
using namespace std;

//then
int main()
{
cout<<"something"<<endl;
cin>>varname;
//so on


Other compilers won't let you do this

#include <iostream.h>

but you should include the libraray

#include <iostream>
//here you need std with every cout or cin Or just once with using namespace std;

HarryW
Feb 22nd, 2001, 08:15 AM
Just to clarify - <iostream> is the standard library, whereas <iostream.h> is the Microsoft modified version of the standard library. I don't think there's any real advantage to using the MS library, except you don't need to add using namespace std with it. Better to use the standatrd library really.

nina2kool
Feb 22nd, 2001, 12:16 PM
Thanks for the response. But you still didn't answer my question (may be because I didn't state my question clear enough). That is:

Why does the C++ book shows
using std::cout;
using std::cin;
using std::endl;
when the program run perfectly okay without them?

What are the purpose of those "using std" statements? I understand the Source File Inclusion (i.e. #include <> ), but I don't understand the "using std" statements.

Thank you very much.

nina.

parksie
Feb 22nd, 2001, 05:29 PM
The using directive imports names from one namespace to another. If you're not in a namespace, then you're automatically in the global namespace, where everything could be preceded by :: if used.

So, what using does, is to allow you to use a name from one namespace in another:

namespace parksie {
int x;
}

using parksie::x;

void main() {
parksie::x = 5;

cout << x << endl; // Prints "5"
}