← Retour au cours: C programming from scratch

Functions and week 3 review

Vidéo bientôt disponible

A function is a named block of code that performs a task and can receive data (parameters) and return a result. They help avoid repeating code, split a big problem into small pieces and test each piece separately. You have already used library functions such as printf and scanf; now you will write your own.

Definition, prototype and call

The definition gives the return type, the name and the list of parameters with their types. The compiler reads the file from top to bottom, so a function must be declared before it is used. To be able to place main first, you write a prototype, which is the header ending in a semicolon. If a function returns nothing its type is void, and if it receives no parameters you write (void) to make clear it accepts none.

c
#include <stdio.h>

int square(int x);                 /* prototype */
double average(double a, double b);
void print_line(int width);

int main(void) {
    printf("square(7) = %d\n", square(7));
    printf("average = %.1f\n", average(4.0, 9.0));
    print_line(20);
    return 0;
}

int square(int x) {
    return x * x;
}

double average(double a, double b) {
    return (a + b) / 2.0;
}

void print_line(int width) {
    for (int i = 0; i < width; i++) {
        putchar('-');
    }
    putchar('\n');
}

Pass by value

In C arguments are always passed by value: the function receives a copy. If it modifies the parameter, the original variable does not change. This detail surprises people coming from other languages. For a function to modify a caller's variable you must pass its address, with pointers, the topic of week 5. For now, if you need a result, return it with return.

c
#include <stdio.h>

static void try_to_change(int n) {
    n = 99;                  /* changes only the local copy */
}

static int is_prime(int n) {
    if (n < 2) {
        return 0;
    }
    for (int d = 2; d * d <= n; d++) {
        if (n % d == 0) {
            return 0;
        }
    }
    return 1;
}

int main(void) {
    int value = 5;
    try_to_change(value);
    printf("value is still %d\n", value);

    for (int i = 1; i <= 20; i++) {
        if (is_prime(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}

Scope and local variables

Variables declared inside a function are local: they exist only while it runs and nobody outside can see them. This lets you reuse names such as i without conflict. Global variables, declared outside every function, are visible in the whole file, but make the program harder to reason about; avoid them except for constants. The word static before a function makes it private to the file, and before a local variable it makes it keep its value between calls.

Recursion

A function can call itself. Every recursive function needs a base case that stops the calls and a step that moves toward that case. Without a base case, calls pile up until the stack is exhausted and the program crashes. Recursion is elegant for problems such as the factorial, but a loop is usually more efficient in C.

c
#include <stdio.h>

static unsigned long long factorial(unsigned int n) {
    if (n <= 1) {
        return 1;                    /* base case */
    }
    return n * factorial(n - 1);     /* smaller problem */
}

static int counter(void) {
    static int calls = 0;            /* keeps its value */
    calls++;
    return calls;
}

int main(void) {
    printf("5! = %llu\n", factorial(5));
    counter();
    counter();
    printf("counter called %d times\n", counter());
    return 0;
}

Common mistake: calling a function before declaring it

If you write main at the top of the file and the helper functions below, the compiler reaches the call without knowing the function and warns with implicit declaration of function. In C17 that is a serious error: it guesses the return type and may return garbage. The solution is to declare a prototype before main, which is just the signature ending in a semicolon, or to place the functions before their first use. Remember also that parameters are passed by value: the function receives a copy, and changing the parameter inside does not modify the caller's variable. If you need to give back a result, use return.

c
#include <stdio.h>

int square(int n); /* prototype: now main can call it */

int main(void) {
    int value = 7;
    printf("%d\n", square(value)); /* 49 */
    printf("%d\n", value);         /* still 7: the function got a copy */
    return 0;
}

int square(int n) {
    n = n * n; /* changes only the local copy */
    return n;
}

Testez vos acquis

Question 1 sur 6

What does for (int i = 0; i < 3; i++) printf("%d ", i); print?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →