Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Questions about using namespace std and cout [duplicate]

Tags:

c++

c

cout

Why do I need to type in using namespace std; in order to be able to use cout and endl? Also what are these called; is cout a function?

Is there cout in C? I heard it was implemented in C++ because it is better in many ways.

like image 710
jlcv Avatar asked Dec 01 '22 20:12

jlcv


2 Answers

cout is a global object defined in the std namespace, and endl is a (stream manipulator) function also defined in the std namespace.

If you take no action to import their names into the global namespace, you won't be able to refer to them with the unqualified identifiers cout and endl. You have to use the fully qualified names:

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

Basically, what using namespace std does is to inject all the names of entities that exist in the std namespace into the global namespace:

using namespace std;
cout << "Hello, Wordl!" << endl;

However, keep in mind that have such a using directive in the global namespace is a BAD programming practice, which will almost certainly lead to evil name clashes.

If you really need to use it (e.g. if a function of yours is using many functions defined in the std namespace, and writing std:: makes the code harder to read), you should rather restrict its scope to the local scope of individual functions:

void my_function_using_a_lot_of_stuff_from_std()
{
    using namespace std;
    cout << "Hello, Wordl!" << endl;

    // Other instructions using entities from the std namespace...
}

Much better, as long as this is practical, is to use the following, less invasive using declarations, which will selectively import only the names you specify:

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

cout << "Hello, Wordl!" << endl;
like image 81
Andy Prowl Avatar answered Dec 14 '22 21:12

Andy Prowl


No! You do not need using namespace std, and you shouldn't use it. Use fully qualified names std::cout and std::endl, or, in a small scope,

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

As for the other questions, std::cout is not a function. It is a kind of global output stream object bound to the standard output. And there isn't an std::cout in C.

like image 22
juanchopanza Avatar answered Dec 14 '22 20:12

juanchopanza