Skip to main content

Section A.4 Types and Declarations

In Python a variable comes into existence the first time you assign to it, and it can hold an integer now and a string later. In C every variable is declared with a type before it is used, and its type never changes. A variable may be declared and given a value on the same line, or declared first and given a value later, although giving every variable a value when you declare it is the better habit:
int count = 0;      // declared and initialized
int total;          // declared only
total = 5;          // assigned later
The type fixes how many bits the variable occupies, and therefore which values it can hold. These are the types we use, with their sizes on the STM32C031C6:
Table A.4.1. Integer types on the STM32C031C6
Type Bits Range
char 8 0 to 255, usually holding a character such as 'A'
int 32 −2,147,483,648 to 2,147,483,647
unsigned int 32 0 to 4,294,967,295
uint8_t 8 0 to 255
uint16_t 16 0 to 65,535
uint32_t 32 0 to 4,294,967,295
The C language does not fix the size of an int: it is 32 bits on our chip and 16 bits on some smaller ones. Code that needs a particular width therefore uses the types from the standard header stdint.h, which the course headers we provide already include. The name describes the type: uint32_t is an unsigned integer of exactly 32 bits. The STM32C031C6’s registers are 32 bits wide, and the device header declares each register as a uint32_t.
A Python integer grows as large as it needs to. A C integer has a fixed number of bits, and an unsigned one wraps around to 0 when it is pushed past its largest value:
uint8_t small = 255;
small = small + 1;      // small is now 0: 256 does not fit in 8 bits
For a signed type such as int, going past the largest value is undefined in C, which means that the language makes no promise at all about the result. In practice, an int usually wraps around to its most negative value, −2,147,483,648, which C names INT_MIN. Because the standard does not require this, however, the compiler is also allowed to assume that an overflow never happens, and with optimization turned on, code that relies on the wraparound can behave unexpectedly. Choose a type large enough for every value the variable will hold.
A U after a number, as in 1U, makes it unsigned. Subsection 1.2.3 explains why register code needs it.
A variable declared without a starting value holds whatever value was left in that memory location before, which is not reliably 0. Counter and sum variables therefore always need to be initialized. Variables declared outside every function are the exception, and start at 0.
C also has float for numbers with a fractional part. The STM32C031C6 has no floating-point hardware, so each float operation is a call to a library routine built from many integer instructions, and we work with integers wherever we can.