Course contentsShow
← C
Lesson 750 of 1,21910. Input and OutputFree lesson

Unbuffered output (stderr)

Unbuffered output (stderr)

What you'll learn: Why the standard error stream displays messages immediately while standard output might wait.

The Waiting Room Analogy

Imagine you are at a post office. To be efficient, the clerk doesn't drive to the airport every time one person drops off a single letter. Instead, they put letters in a bin (a buffer) and wait until the bin is full before sending the truck. This is how printf works; it saves up characters to improve performance.

However, imagine there is a fire in the post office. You wouldn't put a "FIRE!" note in the bin and wait for the truck to fill up. You would scream it immediately. In C, stderr is that scream. It is unbuffered, meaning it bypasses the waiting bin and hits the screen the exact millisecond the command is executed.

Why Use stderr?

In C, printf sends data to stdout (Standard Output). If your program crashes, any text sitting in the stdout buffer might be lost forever because the "truck" never got a chance to leave.

If you are debugging or reporting an error, you use fprintf(stderr, ...). Because it is unbuffered, the message is guaranteed to be printed even if the program crashes immediately on the next line.

Code Example

Watch how we can direct messages to two different streams:

#include <stdio.h>

int main() {
    // This goes to the "bin" (buffered)
    // It might not show up immediately if the program is busy
    printf("Processing data... ");

    // This goes to the "emergency exit" (unbuffered)
    // It shows up the instant it is called
    fprintf(stderr, "ERROR: Connection lost!\n");

    return 0;
}

When to Use Which

Use stdout (via printf) for the actual "work" of your program—things like calculated results or user menus. Use stderr (via fprintf) for diagnostic messages, progress bars, or "Something went wrong" alerts. By keeping errors unbuffered, you ensure that the user—or the developer—knows exactly when and where a problem occurred without any delay.

Key takeaway

stderr is unbuffered, ensuring error messages appear immediately even if the program crashes.