Print or Return?

Beginners often mix up return and printf, because both seem to give out a value. But they do very different things:

  • printf only shows a value to you, in the output. The program can't work with what was printed.
  • return gives the value to the program, which can store it in a variable, calculate with it or print it.

Look at what happens when a function prints its result instead of returning it, and the program then wants to calculate with it:

#include <stdio.h>

void print_sum(int a, int b) {
    printf("%d\n", a + b);
}

int main(void) {
    int result = print_sum(2, 3);
    printf("%d\n", result * 2);
    return 0;
}

The program doesn't compile:

main.c:8:9: error: initializing 'int' with an expression of incompatible type 'void'
    8 |     int result = print_sum(2, 3);
      |         ^        ~~~~~~~~~~~~~~~
1 error generated.

The error message says that a variable of type int can't be initialized with an expression of type void. The function print_sum is void, so it returns nothing that could be stored; it would only print 5. print_sum(2, 3) * 2 ends the same way, only with the error invalid operands to binary expression ('void' and 'int'): you can't calculate with nothing.

The fix is to change void to int and to return the value instead of printing it: return a + b;.

It can also happen the other way round: a function returns a value, but nobody uses it. If you write only add(2, 3); in main, the program prints nothing. The function returned 5, but the program didn't store it or print it, so the value was lost. If you want to see it, print it: printf("%d\n", add(2, 3));.

So when should a function print, and when should it return? A function that calculates something should return the result. The code that calls it then decides what to do with it: print it, store it or keep calculating with it. Print inside a function only when printing is its whole job, as in greet or print_row. Such functions often have names that start with print_, so you can tell them apart at a glance.

Instructions

A pizza costs 9 and a drink costs 3. The function order_price should calculate the price of an order, but it only prints the price, so the program doesn't compile. Fix the function so that it returns the price instead of printing it. The program then prints Together: 63.

The last call in main, order_price(1, 1);, should show the price of a small order. But now it shows nothing: the function returns the price, and nobody uses it. Print it with a label: Small order: 12.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/12