Section A.9 Coding Style
It is very important to have a consistent style when writing code. Here are a few of the myriad reasons it is a good idea to practice good coding standards. Consistent style makes it easier to
-
review other peopleโs code (much easier, in fact),
-
review your own code,
-
share code, and
-
work on code that someone else started.
What follows are some general guidelines developed over many years. There are no hard and fast rules. These guidelines overlap with many other style guides and undoubtedly conflict with some. These are guidelines, not rules. The important thing is that you develop a consistent style that makes your code as readable as possible.
Use the provided template!
template.c is a great place to start good habits. In every file you submit, fill out the top section, indicating what the reader can expect in the rest of the file. In our case, it is very helpful to list the I/O pins your code uses. This will help you avoid the mistake of oversubscribing a pin (mistakenly using it for two functions). The top section also asks for your name, the assignment and a revision history.
Choose a naming style and stick with it.
The two most common naming styles are CamelCase (also called BumpyCase) and snake_case. Pick one and stick to it wherever possible.
Variable names should start with a lowercase letter.
cycleCount is a variable name; CycleCount is not.
Many low-level driver functions take the form
peripheral_function, such as uart2_init or i2c1_byteWrite. This allows you to easily identify the correct function for the particular hardware in your system.
Use lots of comments.
There is a school of thought that says your code should be โself documentingโ and should not require any additional comments. That is a laudable goal, but in practice is never the case. Your comments should describe what a piece of code does, and potentially, why you chose to implement it that way. This will help you remember what you did a week or a year later when you look back at the code.
Your comments should add to the understanding, not just check the box for having comments. Donโt use your comments to explain how the language works: assume your reader is fluent. For example, this is a terrible comment:
int a = 0; /* this is an integer named 'a' which is set to zero */
This is much better (also the variable name makes senseโฆ)
int secondsSinceLastPress = 0; /* Track elapsed time between button presses */
You donโt need to comment every line of code, but place comments above small blocks of code that perform a particular task:
/* loop over the sample array and compute the sum */
int sum = 0;
for (int i = 0; i < NSAMPLES; i++) {
sum += samples[i];
}
Always always always initialize variables.
In regular code, uninitialized variables are hard to find. In embedded code they can be nearly impossible. You will find that every time you try to blink the light, the buzzer buzzes. This is bad enough, but imagine if you were writing code for a heart monitor with an automatic defibrillator! Every time you sampled the pulse, the patient might get zapped. That is definitely not what you are looking for.
Always always always always initialize variables.
Are we clear on this?
Use #define for โmagic numbersโ.
All constants should be declared near the top of the file. This draws attention to them and allows them to be modified easily when needed. Things like I/O bit numbers, divider ratios and delay periods are all good candidates for macros. By declaring them at the top of the file, you provide a single location to change all references to them. At times when you need the same declaration in multiple source files, make it in a
.h file and #include it in all source files that need to reference it.
Use names that make sense.
One of the most frustrating habits is not distinguishing between a bit number and a bit mask. If you have an LED connected to D13 (PA5), which is bit 5 of Port A, it is very handy to have two related
#defines:
#define LED_BIT 5
#define LED_MASK (1U << LED_BIT)
This makes it very obvious which one indicates the consecutive bit number and which one represents the one-hot value used to mask and alter the bit position in a register. Defining
LED_MASK makes reading the uses of it later much easier. With BUZZER_MASK and DEFIB_MASK defined in the same way, compare
GPIOA->ODR |= (LED_MASK | BUZZER_MASK | DEFIB_MASK);
with
GPIOA->ODR |= ((1U << LED_BIT) | (1U << BUZZER_BIT) | (1U << DEFIB_BIT));
The first version allows you to readily see that the LED is going to turn on while the buzzer buzzes and the defibrillator defibrillates. The second version allows you to ponder why the author didnโt read this style guide.
Indentation.
Blocks of code in the same scope should be indented to the same level. Each sub-scope should be indented 4 spaces more than the enclosing scope. For example:
void showNumber(void) {
int interestingNumber = 10;
int numberIsBoring = 0;
if (isPrime(interestingNumber) != 0) {
GPIOA->ODR |= LED_MASK; // an interesting number: LED on
} else {
numberIsBoring = 1;
GPIOA->ODR &= ~LED_MASK; // meh: LED off
}
}
Not:
void showNumber(void) {
int interestingNumber = 10;
int numberIsBoring = 0;
if (isPrime(interestingNumber) != 0) {
GPIOA->ODR |= LED_MASK; // an interesting number: LED on
} else {
numberIsBoring = 1;
GPIOA->ODR &= ~LED_MASK; // meh: LED off
}
}
Indentation makes the code easier to follow and makes variable scope much more obvious.
Braces.
Place the introductory brace on the same line as the statement that begins the new scope. Place the closing brace on a line by itself, except in the if/else case, in which case (as above) it is fine to place the
else { on the same line that closes the if scope:
while (!done) {
done = keepDoingStuff();
}
and
if (isPrime(number)) {
GPIOA->ODR |= LED_MASK; // prime: LED on
} else {
GPIOA->ODR &= ~LED_MASK; // composite: LED off
}
Note: there are times when you can skip the brace. Donโt be tempted! It doesnโt really save any time, and almost universally ends in tears. The one exception is a loop whose body is empty, such as Blinkyโs delay loop,
for (int i = 0; i < 100000; i++);, where the semicolon is the whole body.
