Functions

Article · 3:00

Prototypes, definitions, pass-by-value, and the thing C does not have.

A function has a declaration - the prototype, giving its name, return type and parameter types - and a definition, which is the body. The compiler reads top to bottom, so calling a function defined later in the file requires a prototype earlier, which is what header files are full of. Without one, old C assumed a function returned int and said nothing about its parameters; modern compilers warn, and -Werror=implicit-function-declaration turns that warning into the error it deserves to be.

C passes everything by value. A function receives a copy of each argument, and changing the parameter does not change the caller's variable. There is no pass-by-reference in C. What looks like it is passing a pointer by value: the function receives a copy of an address, and dereferencing that copy reaches the caller's original. This single fact explains why swap(a, b) does nothing and swap(&a, &b) works.

A void return means nothing comes back. A void parameter list means nothing goes in. And a function marked static at file scope is visible only in that file, which is C's only form of privacy - use it for every helper that is not part of a module's public interface.

C has no function overloading and no default arguments. Two functions cannot share a name, which is why the standard library has abs, labs and fabs rather than one abs.

#include <stdio.h>

/* Prototypes: the compiler reads top to bottom and needs to know these
   exist before main calls them. This is what a header file holds. */
int  add(int a, int b);
void swap_wrong(int a, int b);
void swap_right(int *a, int *b);
static int helper(int x);          /* static: this file only */

int main(void)
{
    int x = 1, y = 2;

    printf("%d\n", add(x, y));

    /* C passes EVERYTHING by value. This swaps two copies and the
       copies then go out of scope. */
    swap_wrong(x, y);
    printf("after swap_wrong: %d %d\n", x, y);    /* 1 2 */

    /* This passes copies of two ADDRESSES. Dereferencing a copy of an
       address still reaches the original. */
    swap_right(&x, &y);
    printf("after swap_right: %d %d\n", x, y);    /* 2 1 */

    printf("%d\n", helper(10));
    return 0;
}

int add(int a, int b) { return a + b; }

void swap_wrong(int a, int b)
{
    int t = a; a = b; b = t;       /* local copies only */
}

void swap_right(int *a, int *b)
{
    int t = *a; *a = *b; *b = t;   /* through the addresses */
}

static int helper(int x) { return x * 2; }

/* No overloading in C: two functions cannot share a name. That is why
   the library has abs, labs, llabs and fabs rather than one abs. */