
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between cerr and clog Streams in C++
cerr and clog are both objects of the stderr(standard error) stream, which is used to display error messages or diagnostics. In this article, we will learn the difference between these two in more detail. Further, the description of the cout object is also given to get a clearer picture.
Unbuffered standard error stream (cerr)
The cerr is the standard error stream, which is used to output the errors. This is also an instance of the ostream (as iostream means input/output stream) class. As cerr is unbuffered, therefore it's used when we need to display the error message instantly. It doesn't have a buffer to store the error message and display it later.
Syntax
Here is the following syntax for cerr.
cerr << "Error message" << endl;
Example
#include <iostream> using namespace std; int main() { int age = -1; if (age < 0) { cerr << "Error: Age cannot be negative!" << endl; } else { cout << "Your age is: " << age << endl; } return 0; }
Output
ERROR! Error: Age cannot be negative!
Buffered standard error stream (clog)
The clog is also an instance of the ostream class, which is used to display errors, but unlike cerr, the clog uses a buffer means here, the error will first be inserted into a buffer (memory) and only displayed when:
- The buffer is full.
- The buffer is flushed manually using endl or flush.
- The program ends normally.
This can improve performance when messages are not urgent; it is basically ideal for logging non-critical information, like progress updates.
Syntax
Here is the following syntax for clog.
clog << expression << ... ;
Example
#include <iostream> using namespace std; int main() { clog << "Game started!" << endl; clog << "Player is playing..." << endl; clog << "Game over!" << endl; return 0; }
Output
Game started! Player is playing... Game over!
Standard output stream (cout)
cout is an instance of the ostream class. It is used to produce output on the standard output device, which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator (<<).