Skip to main content

Section A.2 The Shape of a C Program

Here is a short C program for our board. It does nothing visible; it is here to show the parts every program in this book has.
#include "stm32c0xx.h"      // register definitions for our chip

#define START   10          // a named constant
#define LIMIT   (START + 5) // a named expression, in parentheses

/* A comment that runs
   over several lines. */
int main(void) {
    int count = START;      // declare a variable, with a starting value

    while (count < LIMIT) {
        count = count + 1;
    }

    while (1) {
        // the real work of the program goes here, forever
    }
    return 0;               // never reached
}
Semicolons and braces. Each statement ends with a semicolon, and a block of statements is enclosed in braces. Python uses the end of a line and the indentation for these jobs; C uses neither. The compiler would accept the program above written on a single line, so indentation in C is only for the reader. Indent anyway, the way every listing in this book does.
Comments. // starts a comment that runs to the end of the line, and /* … */ encloses a comment of any length. A line that starts with # is not a comment in C. It is a directive to the preprocessor, which edits the text of your file before the compiler translates it.
#include. #include "stm32c0xx.h" pastes the entire contents of the header file stm32c0xx.h into your program at that line. That header defines the names of the chip’s registers. A register is a memory location through which a program controls the hardware, and every program that uses registers starts with a version of this line. GPIOA->ODR, for example, names ODR, the Output Data Register of Port A, and Subsection 1.1.3 explains how to read the arrow. #include plays the role of Python’s import, but it is a literal copy of text rather than a module.
#define. With #define START 10, the preprocessor replaces every later occurrence of START with 10 before the program is compiled. There is no = and no semicolon, and by convention the name is in capitals. Because the replacement is plain text, an expression needs parentheses. Without them, #define LIMIT START + 5 would turn 2 * LIMIT into 2 * 10 + 5, which is 25, not 30. Every #define in this book that holds an expression wraps it in parentheses for this reason.
main. A Python file runs from its first line. A C program starts at the function named main, wherever it is in the file. The int in front of main is the type of the value it returns, and the void in its parentheses means that it takes no inputs. A program for the STM32C031C6 never leaves main: once its setup is done it repeats its work inside while (1) for as long as the board has power. main is still declared to return an int, and every program in this book ends it with return 0;, a line that is never reached.