Skip to content

Small Functions

The Course
•
30 min study

Yesterday's goal checker computed "minutes still missing" inline, in the middle of main. Now suppose the daily report, the weekly report and a test all need that same rule. Copying goal - total into three places means three places to fix when the rule changes, for example when you decide that an exceeded goal should report 0 rather than a negative number. A function gives the rule one name and one definition. Every caller uses the name, and a fix in the definition reaches all of them.

Predict and run

Predict both numbers. Which return statement runs for each call?

Predict before running C
#include <stdio.h>

int remaining(int goal, int done) {
    if (done >= goal) {
        return 0;
    }
    return goal - done;
}

int main(void) {
    printf("%d\n", remaining(60, 25));
    printf("%d\n", remaining(60, 70));
    return 0;
}
Check your prediction
Text
35
0

The first call skipped the if and returned 60 minus 25. The second call met the if, and return 0; ended the function immediately: the subtraction line never ran. A return does not just provide a value, it leaves the function. Try remaining(60, 60) and decide which line handles the exact boundary.

Anatomy of a function

int remaining(int goal, int done) is read from left to right:

  • int is the return type: the kind of value the function hands back.
  • remaining is its name.
  • (int goal, int done) are its parameters, each with its own type.
  • The body in braces does the work, and return gives the result to the caller.

At a call such as remaining(60, 25), the values in parentheses are the arguments. C evaluates each argument, copies the values into the parameters in order, runs the body, and replaces the call with the returned value. Order matters: remaining(25, 60) would mean a goal of 25 with 60 done, and return 0. The names do not connect anything; only the positions do.

One rule, many callers C
#include <stdio.h>

int hours_part(int minutes) {
    return minutes / 60;
}

int minutes_part(int minutes) {
    return minutes % 60;
}

int main(void) {
    int day = 95;
    int week = 410;
    printf("Day: %d:%02d\n", hours_part(day), minutes_part(day));
    printf("Week: %d:%02d\n", hours_part(week), minutes_part(week));
    return 0;
}
Text
Day: 1:35
Week: 6:50

Notice what the functions do not do: they do not print. They compute and return, and main decides how to show the result. A function that returns a value can be used in a report, in a comparison, in another calculation or in a test. A function that prints can only print. Keep those jobs apart.

Every path must return a value

A function with a non-void return type promises a value on every path through its body. This version forgets one path:

C
int remaining(int goal, int done) {
    if (done < goal) {
        return goal - done;
    }
}

When done reaches the goal, the function falls off the closing brace without a return. If the caller uses the result, the behavior is undefined: the caller may receive whatever happened to be in a register, and it may differ between compilers and settings. Compilers warn that control reaches the end of a non-void function. Read that warning as "one of your cases has no answer".

Declare before you call

The compiler reads your file from top to bottom. When it reaches a call, it must already know the function's name, parameters and return type. Put a definition below main and call it from main, and C17 compilers reject the call:

Shell
error: call to undeclared function 'remaining'; ISO C99 and later do not support implicit function declarations

You have two fixes. Define the function above main, as the examples so far do, or write a declaration (also called a prototype) near the top. A declaration is the first line of the function followed by a semicolon. It promises that a definition exists elsewhere.

A declaration lets main come first C
#include <stdio.h>

int remaining(int goal, int done);

int main(void) {
    printf("%d\n", remaining(90, 30));
    return 0;
}

int remaining(int goal, int done) {
    if (done >= goal) {
        return 0;
    }
    return goal - done;
}
Text
60

On Day 6 you will move declarations into a header file so that several source files can share one function.

Practice

Exercise

Your turn

Write int sessions_needed(int goal, int per_session) that returns how many whole sessions of per_session minutes it takes to reach goal minutes. A partial session still counts as a whole one, and a goal of 0 or less needs 0 sessions. Assume per_session is positive. Print the results of three calls on one line:

Text
4 5 0

for (100, 25), (110, 25) and (0, 25).

Your workspace C
#include <stdio.h>

int main(void) {
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Integer division rounds down: 110 / 25 is 4. You need to round up when there is a remainder, so check % and add one session when it is not zero.

Hint 2: a first step

Handle the empty goal first: if the goal is 0 or less, return 0 straight away. Then compute int sessions = goal / per_session; and decide whether to add one.

Show one solution
C
#include <stdio.h>

int sessions_needed(int goal, int per_session) {
    if (goal <= 0) {
        return 0;
    }
    int sessions = goal / per_session;
    if (goal % per_session != 0) {
        sessions++;
    }
    return sessions;
}

int main(void) {
    printf("%d %d %d\n", sessions_needed(100, 25), sessions_needed(110, 25), sessions_needed(0, 25));
    return 0;
}
Text
4 5 0

Every path through the function ends in a return, and the early return keeps the main calculation free of special cases. The function never prints, so the same rule could feed a report or an assertion. The brief said to assume per_session is positive because dividing by zero is undefined; a caller that might pass 0 must check first. Next you will see exactly what a function can and cannot change in its caller.

Was this article helpful?

Your response is saved on this device.