1
votes

I’m having some trouble understanding the preprocessor and namespaces in C++. For example, consider the following program:

#include <iostream> 

int main() 
{
    using namespace std;

    cout << "Hello World!" << endl;

    return 0; 
}

So when this program is getting ready to be compiled, the preprocessor will recognize the #include directive and add the iostream file to the program so that the program will have I/O capability (ie “cout” and “endl”). Now according to my textbook the classes, functions, and variables that are a standard component of C++ compilers are placed in the namespace std.

This is confusing because if the standard functions (“cout” and “endl”) are placed in this namespace what is the purpose of iostream? I’m basically trying to understand why we need both iostream and some information about the namespace in use.

2

2 Answers

3
votes

Strictly speaking, you do not need using namespace std; All it does is letting you write

cout << "Hello World!" << endl;

instead of

std::cout << "Hello World!" << std::endl;

The namespace "contains" iostream definitions (among other definitions provided by the standard C++ library) only in the sense that std:: is implicitly "prefixed" to all names. This "contains" is different from the "contains" in "the iostream file contains definitions of input/output functions": the file literally contains the definitions; the std:: namespace name is only a prefix that lets you avoid name collisions.

1
votes

The header file <iostream> includes declarations of several useful things, including the variables std::cout and std::endl.

Without these declarations, the compiler wouldn't know what you were referring to when you write cout << ....