100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

cerr and clog in C++

Understand the difference between `cerr` and `clog` in C++ for writing error and log messages, including buffering behavior.

Input & OutputBeginner5 min readJul 7, 2026
Analogies

1. Intro

cerr and clog are standard stream objects, like cout, used to write output to the standard error stream instead of standard output. They are commonly used for reporting errors, warnings, and diagnostic/log messages, keeping them separate from normal program output.

🏏

Cricket analogy: A stadium PA announcer keeps urgent safety alerts on a separate channel from the regular match commentary, just as cerr and clog route error and diagnostic messages to a separate stream from cout's normal program output.

2. Syntax

cpp
cerr << "error message";
clog << "log message";

3. Explanation

Both cerr and clog write to the standard error stream (stderr), but they differ in buffering. cerr is unbuffered by default, meaning each message is flushed and displayed immediately — ideal for critical errors that must be seen right away, even if the program crashes afterward. clog is buffered, so its output may be held temporarily and flushed later (e.g., when the buffer is full or the program ends normally), which is more efficient for routine logging where instant display is not critical.

🏏

Cricket analogy: cerr is like an umpire's immediate signal for a serious infraction — shown the instant it happens, unbuffered, even if the match is abandoned right after — while clog is like a scorer's routine notes jotted down and only compiled into the official record at the end of the innings, buffered for efficiency.

Because cerr is unbuffered, using it heavily for non-critical messages can slow down a program. Prefer clog for high-volume logging and reserve cerr for genuine, immediate error reporting.

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    int divisor = 0;

    clog << "Starting division check..." << endl;

    if (divisor == 0) {
        cerr << "Error: division by zero attempted!" << endl;
        return 1;
    }

    cout << "Result: " << (10 / divisor) << endl;
    return 0;
}

5. Output

text
Starting division check...
Error: division by zero attempted!

6. Key Takeaways

  • cerr and clog both write to the standard error stream, separate from cout.
  • cerr is unbuffered, so messages appear immediately — best for urgent errors.
  • clog is buffered, so messages may be delayed — best for routine logging.
  • Redirecting stdout in a shell does not redirect cerr/clog output, since they target stderr.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#CerrAndClogInC#Cerr#Clog#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep