Learn/C/6. Functions
Lesson 6 of 15
Sign in

C, lesson 6

Functions

A function is a named piece of code you can call whenever you need it. Functions let you write a calculation once, give it a meaningful name, and test it on its own. You have been calling functions since lesson 1 (printf, scanf); now you will write your own.

The first line of a function is its signature:

  • double is the return type, the kind of value the function hands back.
  • area_of_rectangle is the name.
  • (double width, double height) is the parameter list. Each parameter has a type and a name, and acts like a local variable that starts with the value the caller passed.

return ends the function and sends a value back. A function that returns nothing has the return type void, and may use a bare to leave early.

2 exercises to try what you just read.

Exercise 1

Prime checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Simplify a fraction

Press Ctrl Enter or Check to test your code.

return;

A function that takes no parameters is written int roll(void). Since C23, empty parentheses int roll() mean the same thing, but (void) is still very common and you will see it everywhere.

Declare before use

The compiler reads your file from top to bottom. If main calls a function that is defined lower down, put a prototype (the signature followed by a semicolon) near the top:

Arguments are copied

C passes arguments by value: the function gets its own copy. Changing a parameter inside the function has no effect on the caller's variable.

To let a function change the caller's variable, you pass its address instead. That is what scanf does with &, and you will learn how to write such functions in the pointers lesson.

Scope

A variable declared inside a pair of braces exists only inside those braces. That is its scope. Two functions can each have a local variable called total, and they never interfere. Variables declared outside every function are global: every function can see and change them. Globals make programs harder to reason about, so pass values through parameters instead.

A local variable marked static is the exception to the rule that locals disappear: it keeps its value between calls.

Good functions

A good function does one job, has a name that is a verb or a question (print_receipt, is_valid), and is short enough to read without scrolling. When main starts to grow, look for a block of lines you could name, and move it into a function.

Further reading

  • cppreference: Function definitions
  • cppreference: Function declarations
  • cppreference: Storage-class specifiers (static)
  • GNU C Manual: Functions

Write a function bool is_prime(int n) that returns true when n is a prime number (a whole number greater than 1 whose only divisors are 1 and itself). Then read integers until the input ends, and for each one print <n> is prime or <n> is not prime.

Tip: you only need to try divisors d while d * d <= n.

Write a function int gcd(int a, int b) that returns the greatest common divisor of two non-negative integers using Euclid's method: while b is not 0, replace (a, b) with (b, a % b); then a is the answer.

Read a numerator and a denominator (numerator ≥ 0, denominator > 0) and print the fraction in lowest terms as numerator/denominator.

#include <stdio.h>

double area_of_rectangle(double width, double height) {
    return width * height;
}

int main(void) {
    double a = area_of_rectangle(3.0, 4.5);
    printf("%.2f\n", a);    // 13.50
    return 0;
}
void print_stars(int count) {
    for (int i = 0; i < count; i++) {
        putchar('*');
    }
    putchar('\n');
}
int square(int n);          // prototype: "this exists, trust me"

int main(void) {
    printf("%d\n", square(9));
    return 0;
}

int square(int n) {         // definition
    return n * n;
}
void reset(int score) {
    score = 0;              // changes the copy only
}

int main(void) {
    int score = 42;
    reset(score);
    printf("%d\n", score);  // still 42
}
int next_ticket(void) {
    static int last = 100;  // set once, remembered between calls
    last++;
    return last;            // 101, then 102, then 103...
}
Input:
7 10 1
Output:
7 is prime
10 is not prime
1 is not prime
Input:
6 8
Output:
3/4