C++ cerr & clog
In this page:
Standard Error stream (cerr)
cerr is the standard error stream, meant specifically for reporting problems rather than normal program output. Crucially, cerr is unbuffered, so every message written to it appears on screen instantly rather than waiting to be flushed — exactly what you want when reporting a crash or a fatal error.
Example: Standard Error stream (cerr)
#include <iostream>
int main() {
std::cerr << "Fatal error: file not found" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Log Stream (clog)
clog is the standard log stream, intended for diagnostic or status messages that aren't urgent enough to need cerr's instant display. Unlike cerr, clog is buffered, meaning it collects output in memory and writes it in efficient batches, which is better suited to frequent logging that shouldn't slow down your program.
Example: Log Stream (clog)
#include <iostream>
int main() {
std::clog << "Status: request processed" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
cerr vs cout
cout and cerr both print to the terminal, but keeping them separate lets you redirect one without the other — for example, sending cout to a results file while cerr still shows errors on screen. This separation is exactly why command-line tools distinguish output from errors in the first place.
Example: cerr vs cout
#include <iostream>
int main() {
std::cout << "Result: 42" << std::endl; // can be redirected separately
std::cerr << "Warning: low disk space" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
clog vs cerr
clog and cerr both target the same error destination conceptually, but differ in urgency and performance: reach for cerr when a message needs to appear the instant it happens, like a fatal error, and clog for background diagnostic logging where a small delay from buffering is perfectly acceptable.
Example: clog vs cerr
#include <iostream>
int main() {
std::cerr << "Immediate: connection lost" << std::endl;
std::clog << "Background: cache refreshed" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Handling Runtime Errors
Writing errors to cerr instead of cout guarantees they're still visible even if a user redirects your program's normal output to a file with something like myprogram > results.txt, since that redirection only affects cout, not cerr. This is why well-behaved command-line programs never mix error messages into their cout output.
Example: Handling Runtime Errors
#include <iostream>
int main() {
std::cout << "Normal output" << std::endl;
std::cerr << "Error output stays visible even if cout is redirected" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: