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

When to use fflush(stdout)

When to use fflush(stdout)

What you'll learn: How to force the computer to display your output immediately instead of waiting for a full buffer or a newline character.

The Waiting Room Analogy

Think of the stdout (standard output) stream like a small bus. To be efficient, the bus doesn't leave the station every time a single passenger (a character) arrives. Instead, it waits until it is full or until a specific "departure signal" is given.

In C, output is usually buffered. This means when you call printf(), your text is stored in a hidden memory area (the buffer) rather than being sent directly to the screen. Normally, the "departure signal" is a newline character (\n). When the program sees a newline, it drives the bus to the screen. But what happens if you want to display text without a newline, or if your program crashes before the bus leaves?

The Solution: fflush()

The fflush(stdout) function is your way of telling the computer, "Don't wait for the bus to fill up; send whatever is currently in the buffer right now."

This is critical in two main scenarios:

  1. Progress Bars or Prompts: If you print a message like "Loading..." without a \n because you want the percentage to appear on the same line, the user might see nothing but a blank screen for seconds because the text is stuck in the buffer.
  2. Debugging: If your program crashes, any text sitting in the buffer is lost forever. By flushing the output, you ensure your "Reached step 2" message actually appears on the screen before the crash happens.

Code Example

Notice how we use fflush here to ensure the user sees the prompt before the program pauses for input.

#include <stdio.h>
#include <unistd.h> // for sleep()

int main() {
    printf("Connecting to server... ");
    
    // Without this, "Connecting to server..." might not 
    // show up until the sleep timer is finished!
    fflush(stdout);
    
    // Simulate a long process
    sleep(2);
    
    printf("Done!\n");
    return 0;
}

Why not use it every time?

Writing to the screen is "expensive" in terms of performance. If you flush after every single character, your program will run significantly slower. Use fflush(stdout) intentionally: when you need immediate visual feedback without a newline.

Key takeaway

Use fflush(stdout) to manually push data from the memory buffer to the screen when you aren't using a newline character.