Skip to main content

Section A.7 Functions, Prototypes and Scope

This program declares, calls and defines one function, addingFunc.
#include "stm32c0xx.h"

int addingFunc(int x, int y);           // function prototype

int main(void) {
    int res = addingFunc(3, 9);         // res is 12

    while (1) {
    }
    return 0;                           // never reached
}

/* Inputs: two integers to be added.
 * Output: the result of the addition. */
int addingFunc(int x, int y) {
    int result = x + y;
    return result;
}
Types in the first line. A Python def names only the function and its parameters. A C function also gives the type of the value it returns, in front of its name, and the type of each parameter. A function that returns nothing has the return type void. Arguments passed to a function when it is called do not include data types, as in addingFunc(3, 9). Their types should match the types in the function declaration, because C converts one number type to another without a warning: passing 2.7 to an int parameter passes 2.
Prototypes. The compiler processes a file from top to bottom, once, so a function has to be declared before the first line that calls it. A prototype is the function’s first line with a semicolon in place of its body. It gives the return type, the function name and the parameter types, and once it is in place the full definition can come later in the file, or in a different file altogether. Function prototypes go at the top of the program, after the #include lines.
A header file consists mostly of prototypes and #defines. The course’s delay_ms() function, for example, is defined in sysinit.c, and its prototype is in ES28.h, so a program that includes ES28.h can call it.
Passing arguments. A function receives copies of the values it is called with. Assigning to x inside addingFunc would change its own copy and nothing in main.
Scope. A variable declared inside a pair of braces exists only inside those braces, and the variable declared in a for loop’s first part exists only inside that loop. Python’s loop variable is still there after the loop ends; C’s is not. This is why Blinky can declare int i in one delay loop and then again in the next.
A variable declared outside every function is global. Global variables are accessible by all functions in the program, and their value can be changed throughout the program. In C a function changes a global variable by assigning to it; there is no equivalent of Python’s global keyword.