Structs, enums and typedef
Grouping values into structs, the dot and the arrow, naming choices with enum, and shorter names with typedef.
Grouping values that belong together
A temperature sensor reading is not one number. It has a value, the channel it came from and whether it is valid. You could keep three separate variables, but as soon as you have ten sensors you have thirty variables and nothing to say which ones go together.
A struct bundles several values into one new type. Each value inside is a member, and you reach it with a dot.
#include <stdio.h>
struct reading {
int channel;
int value;
int valid;
};
int main(void) {
struct reading r;
r.channel = 2;
r.value = 215;
r.valid = 1;
printf("channel %d: %d (valid %d)\n", r.channel, r.value, r.valid);
return 0;
}
The block that starts struct reading { ... }; describes a shape and creates no variable. The line struct reading r; creates one variable of that shape. Note the semicolon after the closing brace: forgetting it is the most common first error with structs.
Giving a struct its starting values
Like an array, a struct can be filled in where it is declared. Naming each member is clearer and keeps working if someone later reorders the members. Any member you leave out starts at zero.
#include <stdio.h>
struct reading {
int channel;
int value;
int valid;
};
int main(void) {
struct reading a = { 1, 180, 1 }; // in member order
struct reading b = { .channel = 3, .value = 202 }; // by name; valid becomes 0
printf("a: channel %d value %d valid %d\n", a.channel, a.value, a.valid);
printf("b: channel %d value %d valid %d\n", b.channel, b.value, b.valid);
return 0;
}
Copying a struct
Assigning one struct to another copies every member. Afterwards the two are separate variables, so changing one leaves the other alone.
#include <stdio.h>
struct point {
int x;
int y;
};
int main(void) {
struct point a = { .x = 1, .y = 2 };
struct point b = a; // copies x and y
b.x = 50;
printf("a = (%d, %d) b = (%d, %d)\n", a.x, a.y, b.x, b.y);
return 0;
}
C cannot compare two structs with ==. To ask whether they are equal, compare the members you care about.
struct point {
int x;
int y;
};
int main(void) {
struct point a = { 1, 2 };
struct point b = { 1, 2 };
return a == b; // not allowed: compare a.x == b.x && a.y == b.y
}
Structs and functions
A struct can be passed to a function and returned from one. As with any other argument, the function receives a copy.
#include <stdio.h>
struct point {
int x;
int y;
};
struct point add(struct point a, struct point b) {
struct point sum = { a.x + b.x, a.y + b.y };
return sum;
}
int main(void) {
struct point p = add((struct point){ 1, 2 }, (struct point){ 10, 20 });
printf("(%d, %d)\n", p.x, p.y);
return 0;
}
The (struct point){ 1, 2 } form builds a temporary struct right where it is needed.
To change the caller's struct, pass its address, exactly as in the last lesson. Reaching a member through a pointer is so common that C has an arrow for it: p->x means (*p).x.
#include <stdio.h>
struct counter {
int count;
int limit;
};
void tick(struct counter *c) {
if (c->count < c->limit) {
c->count++; // the same as (*c).count++
}
}
int main(void) {
struct counter presses = { .count = 0, .limit = 3 };
for (int i = 0; i < 5; i++) {
tick(&presses);
}
printf("count stopped at %d\n", presses.count);
return 0;
}
Use a dot when you have the struct itself and an arrow when you have a pointer to it. Firmware usually passes a pointer even when the function only reads, because copying a large struct costs time and stack. It adds const to promise it will not change anything: void show(const struct counter *c).
Arrays of structs
Ten sensors become one array, and a loop handles all of them.
#include <stdio.h>
struct reading {
int channel;
int value;
};
int main(void) {
struct reading log[] = {
{ 0, 180 },
{ 1, 215 },
{ 2, 197 },
};
int n = sizeof log / sizeof log[0];
int highest = 0;
for (int i = 1; i < n; i++) {
if (log[i].value > log[highest].value) {
highest = i;
}
}
printf("channel %d is highest at %d\n", log[highest].channel, log[highest].value);
return 0;
}
log[i].value reads left to right: element i of the array, then its value member.
Shorter names with typedef
Writing struct reading everywhere gets long. typedef gives an existing type a second name. Embedded code usually ends these names in _t.
#include <stdio.h>
typedef struct {
int x;
int y;
} point_t;
typedef unsigned char byte_t; // typedef works for any type, not only structs
int main(void) {
point_t p = { 3, 4 };
byte_t b = 200;
printf("(%d, %d) %d\n", p.x, p.y, b);
return 0;
}
typedef creates no new kind of value. byte_t and unsigned char are the same type with two names. The fixed-width types you will meet in the next stage, such as uint8_t and uint32_t, are typedefs too.
Naming a set of choices with enum
Firmware is full of values that can only be one of a few things: a motor is stopped, starting or running; a function succeeded or failed in one of several ways. Using bare numbers like 2 for "running" makes code hard to read. An enum gives each choice a name.
#include <stdio.h>
typedef enum {
MOTOR_STOPPED, // 0
MOTOR_STARTING, // 1
MOTOR_RUNNING, // 2
} motor_state_t;
const char *state_name(motor_state_t s) {
switch (s) {
case MOTOR_STOPPED: return "stopped";
case MOTOR_STARTING: return "starting";
case MOTOR_RUNNING: return "running";
}
return "unknown";
}
int main(void) {
motor_state_t state = MOTOR_STOPPED;
for (int step = 0; step < 3; step++) {
printf("%s\n", state_name(state));
if (state == MOTOR_STOPPED) {
state = MOTOR_STARTING;
} else if (state == MOTOR_STARTING) {
state = MOTOR_RUNNING;
}
}
return 0;
}
The names count up from 0 unless you say otherwise. You can give any of them a value, which is how error codes are usually written.
#include <stdio.h>
typedef enum {
STATUS_OK = 0,
STATUS_TIMEOUT = -1,
STATUS_BAD_ARG = -2,
} status_t;
status_t set_speed(int rpm) {
if (rpm < 0 || rpm > 3000) {
return STATUS_BAD_ARG;
}
return STATUS_OK;
}
int main(void) {
printf("%d %d\n", set_speed(1500), set_speed(9000));
return 0;
}
An enum value is an ordinary integer underneath. The names exist for the people reading the code, and a switch on an enum is the clearest way to handle each case.
Putting it together
Real firmware combines all three: a typedef'd struct that holds an enum state and some data, passed around by pointer.
#include <stdio.h>
typedef enum { LED_OFF, LED_ON } led_state_t;
typedef struct {
int pin;
led_state_t state;
int toggles;
} led_t;
void led_toggle(led_t *led) {
led->state = (led->state == LED_OFF) ? LED_ON : LED_OFF;
led->toggles++;
}
int main(void) {
led_t status = { .pin = 13, .state = LED_OFF };
led_toggle(&status);
led_toggle(&status);
led_toggle(&status);
printf("pin %d is %s after %d toggles\n",
status.pin, status.state == LED_ON ? "on" : "off", status.toggles);
return 0;
}
Where this leads
You now have every piece of C a beginner needs. Structs reappear throughout the course. In the next stage you will see how a struct is laid out in memory, why the compiler sometimes leaves gaps between members, and how a struct placed at a fixed address lets firmware read a whole peripheral's registers with UART1->DR, which is the arrow you learned here.
Common mistakes
- Forgetting the semicolon after the closing brace of a struct or enum definition.
- Using
.on a pointer or->on a struct. Dot for the struct, arrow for a pointer to it. - Expecting a function to change a struct that was passed by value. It changed a copy; pass a pointer.
- Comparing structs with
==. Compare the members. - Using bare numbers where an enum name would say what the number means.
Interview question: What is the difference between a struct and an array?
Answer: An array holds several values of the same type, reached by position with an index such as a[2]. A struct holds values that can each have a different type, reached by name such as r.value. Arrays suit many of the same thing, like samples from one sensor; structs suit the different facts about one thing, like a reading's channel, value and validity. They combine: an array of structs is the usual way to hold a table of records.
In the product: a smart lock
A smart lock knows its users and what state the bolt is in. A struct keeps each user's details together, and an enum names the states.
#include <stdio.h>
enum bolt { LOCKED, UNLOCKED, JAMMED };
struct user {
const char *name;
int code;
int from_hour, to_hour; // when this code works
};
int main(void) {
struct user cleaner = { "cleaner", 4711, 9, 12 };
enum bolt state = LOCKED;
int hour = 10, typed = 4711;
if (typed == cleaner.code && hour >= cleaner.from_hour && hour < cleaner.to_hour) state = UNLOCKED;
printf("%s: %s\n", cleaner.name, state == UNLOCKED ? "unlocked" : "still locked");
return 0;
}
Build it: recipe mode
This is step 7, the last of the module project. The premium scale has a recipe mode: it walks you through each ingredient, shows how much is still missing, and adds up the whole bowl. Each ingredient has a name, a target and what has been weighed so far, so it is a struct.
Lab: Recipe mode with an array of structs
The struct ingredient_t and the enum status_t are provided.
status_of(ing)returnsST_TODOwhen nothing has been weighed (0 g),ST_SHORTwhen some but less than the target,ST_OKwhen within 5 g of the target either way, andST_OVERwhen more than 5 g above it. Check them so thatST_OKwins overST_SHORT(a 2 g shortfall is fine).total_weighed(r, n)returns the sum of theweighedgrams of allningredients.next_todo(r, n)returns the index of the first ingredient that is not yetST_OKorST_OVER, or -1 when everything is done.
Going deeper
Interview question: What could go wrong in a smart lock's firmware, and how would you design against it?
Answer: The bolt can jam (detect it with a position sensor and a motor current limit, and report it rather than retrying forever), the battery can run low (warn early and keep enough energy to unlock), the radio can be attacked (authenticated, encrypted commands with replay protection), and the firmware can hang (a watchdog that restarts into a safe state, and the bolt holds its position without power). Above all, a person must always be able to get out from inside.
Interview question: Why do embedded programmers often pass a pointer to a struct instead of the struct itself?
Answer: Passing a struct by value copies every member onto the stack, which costs time and stack space, and a microcontroller may have only a few kilobytes of stack. Passing a pointer copies just one address. A pointer also lets the function update the caller's struct. When the function only reads, the parameter is declared const, so the caller still gets the guarantee that nothing changes.
Interview question: Why use an enum instead of #define constants for a set of states?
Answer: An enum groups related names under one type, so a function parameter of type motor_state_t says what values are expected where a plain int does not. Enum names follow C's scope rules and show up by name in a debugger, while #define names are replaced by the preprocessor before compiling. Many compilers also warn when a switch on an enum misses a case, which catches a forgotten state. Underneath, enum values are ordinary integers, so they cost nothing extra.
Explain it: In your own words, explain what c->count++ does when c is a pointer to a struct with a count member.
Answer: c holds the address of a struct somewhere else in memory. The arrow follows that address and selects the struct's count member, the same as writing (*c).count. The ++ then adds one to that member. Because it works through the address, it changes the original struct, not a copy, so the caller sees the new count.