Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between cout<<cout and cout<<&cout in c++?

Tags:

c++

cout

This might be a beginner question and understanding how cout works is probably key here. If somebody could link to a good explanation, it would be great. cout<<cout and cout<<&cout print hex values separated by 4 on a linux x86 machine.

like image 773
byslexia Avatar asked Sep 20 '11 17:09

byslexia


People also ask

What is << cout?

cout in C++ It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).

What is the meaning of std :: cout in C++?

std::cout is used to output a value (cout = character output) std::cin is used to get an input value (cin = character input) << is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console).

What is the difference between Cout and print?

cout is a reserved word. print is not, in c++. cout is the standard function to write something on the standard OUTput (screen, nowadays, printer before). Formely print, tells a programm to print on printer, cout on the screen.


2 Answers

cout << cout is equivalent to cout << cout.operator void *(). This is the idiom used before C++11 to determine if an iostream is in a failure state, and is implemented in std::ios_base; it usually returns the address of static_cast<std::ios_base *>(&cout).

cout << &cout prints out the address of cout.

Since std::ios_base is a virtual base class of cout, it may not necessarily be contiguous with cout. That is why it prints a different address.

like image 72
MSN Avatar answered Oct 21 '22 20:10

MSN


cout << cout is using the built-in conversion to void* that exists for boolean test purposes. For some uninteresting reason your implementation uses an address that is 4 bytes into the std::cout object. In C++11 this conversion was removed, and this should not compile.

cout << &cout is printing the address of the std::cout object.

like image 33
R. Martinho Fernandes Avatar answered Oct 21 '22 21:10

R. Martinho Fernandes