Learn C++
#include "ioformatting/cerr_clog.hpp"

cerr and clog: Error Streams in C++

//concept

Beyond cout, C++ provides std::cerr (errors, unbuffered) and std::clog (logs, buffered) — all three usually reach the same terminal, but they are separate streams the caller can redirect independently. The classic split: program output goes to cout so it can be piped into files or other programs, while diagnostics go to cerr so they still reach the human.

cerr is unbuffered (every write appears immediately, even mid-crash), while clog buffers like cout for efficiency. Reaching for cerr for errors is what makes ./app > out.txt capture results while errors still print to the screen.

//how it works
1

Three streams, three jobs

cout carries normal output, cerr carries errors immediately, clog carries buffered logging — same syntax (<<), different destinations.

2

Redirection splits them

./app > results.txt sends only cout to the file; cerr keeps printing to the terminal, so errors are never buried in data.

3

cerr is unbuffered

Every cerr write hits the terminal at once — slower, but crash-safe, which is exactly what error reporting needs.

4

clog for volume

Routine logging belongs on clog: buffered like cout for speed, yet separable from real output when redirected.

//example
#include <iostream>
 
int main() {
int value = -3;
if (value < 0) {
std::cerr << "error: negative value" << std::endl;
return 1;
}
std::cout << value << std::endl;
return 0;
}
Output
error: negative value
1The negative check fails validation, so the program takes the error branch.
2The message goes to cerr, not cout — on screen they look identical, but redirection treats them separately.
3Returning 1 (nonzero) signals failure to the calling shell, the standard error convention.
//use cases
Keeping pipelines clean: data on cout, complaints on cerr
Crash-safe diagnostics that appear even when buffers never flush
CLI tools whose stdout is consumed by other programs
Nonzero exit codes paired with cerr messages as the Unix error contract

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.