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

The return value of printf

The return value of printf

What you'll learn: How to use the integer value returned by the printf function to track the exact number of characters printed to the screen.

More than just a screen writer

Up until now, you have likely used printf as a "fire and forget" tool. You tell it what to say, and it displays it on the screen. However, in C, almost every function provides feedback to the programmer. printf is no different; it doesn't just perform an action, it also reports back a specific piece of data.

Think of printf like a professional sign-painter. You give them a message to paint on a wall. Once they are finished, they don't just walk away; they hand you a receipt stating exactly how many letters and spaces they painted. In C, this "receipt" is an integer value.

The character count

When printf finishes its job, it returns an int. This number represents the total count of characters successfully sent to the output. This includes letters, numbers, punctuation, spaces, and even invisible characters like the newline (\n).

If something goes wrong (like the output stream being closed), it returns a negative number, but in 99% of daily coding, you’ll use it to measure the length of your output.

Seeing it in action

You can capture this return value by assigning the printf call to an integer variable. This is particularly useful when you need to align text or build dynamic interfaces where the length of the words might change.

#include <stdio.h>

int main() {
    int charactersPrinted;

    // printf performs its action AND returns a value
    charactersPrinted = printf("Hello, World!\n");

    // "Hello, World!" is 13 characters + 1 for the newline = 14
    printf("The previous line was %d characters long.\n", charactersPrinted);

    return 0;
}

In the example above, printf prints the greeting first. Then, it hands the number 14 to the variable charactersPrinted. We then use a second printf to report that count.

Why does this matter?

While it seems simple, this return value is the secret to creating clean, professional terminal layouts. If you are building a table and need to draw a subray of dashes (---) that is exactly as long as a user's name, you don't have to guess the length. You simply ask printf how many characters it just printed and use that number to draw your line.

Key takeaway

The printf function returns an integer representing the total number of characters printed, or a negative value if an error occurred.