Functions in C

Functions are central in C. We’ll learn about functions with a few different examples.

#include <stdio.h>

// Here's a function that takes two ints and returns
// their sum as an int.
int plus(int a, int b) {
    // C requires explicit returns, i.e. it won't
    // automatically return the value of the last
    // expression.
    return a + b;
}

// In C, we can't omit the type name for parameters
// even if they are of the same type.
int plusPlus(int a, int b, int c) {
    return a + b + c;
}

int main() {
    // Call a function just as you'd expect, with
    // name(args).
    int res = plus(1, 2);
    printf("1+2 = %d\n", res);

    res = plusPlus(1, 2, 3);
    printf("1+2+3 = %d\n", res);

    return 0;
}

To compile and run the program:

$ gcc functions.c -o functions
$ ./functions
1+2 = 3
1+2+3 = 6

There are several other features to C functions. One is passing pointers to functions, which allows for modification of variables outside the function scope.