I came across a piece of code that does basically the following:
#include <iostream>
using namespace std;
int main()
{
cout << cerr << " Hi.";
return 0;
}
Output:
0x601088 Hi.
First of all, why would anyone do 'cout << cerr' it does not make sense. Second of all, what is the meaning of the output above?
Worth to mention that on my machine the above code compiles and executes without errors.
However a much more complex code (doing the same thing as above) on a different machine (server ssh connection) running the same version of gcc 5.4.0, produces this error when doing make (shortened for clarity):
error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::ostream {aka std::basic_ostream<char>}’)
cout << cerr << "DB: Field " + e.table + "[" + e.index + "]." + e.field
Any thoughts on this?
cout is an object of the stdout stream, while cerr is an object of the stderr stream. stdout and stderr are different streams, even though they both refer to console output by default.
cout is buffered, cerr is not, so cout should be faster in most cases. (Although if you really care about speed, the C output functions such as printf tend to be a lot faster than cout/cerr). cout and cerr are ostream objects.
The cerr object is used along with the insertion operator << in order to display error messages. For example, int var1 = 25, var2 = 50; cerr << var1; cerr << "Some String"; cerr << var2; The << operator can be used more than once with a combination of variables, strings, and manipulators (like endl ):
The “c” in cerr refers to “character” and 'err' means “error”, Hence cerr means “character error”. It is always a good practice to use cerr to display errors.
Until c++11, std::basic_ios
offered an implicit conversion to void*
. This code won't compile with c++11 or later. You basically have this, which compiles with older versions of gcc :
#include <iostream>
int main()
{
void * x = std::cerr;
std::cout << x << " Hi.";
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With