Structs, enums and unions
Real data has several parts: a product has a name, a price and a stock count. A struct groups those values into one type. An enum gives names to a set of choices, and a union stores one of several types in the same memory. Together they're how C models everything from file headers to network packets to game entities.
Defining a struct
#include <stdio.h>
struct product {
char name[32];
int price_cents;
int stock;
};
int main(void) {
struct product p = {"Keyboard", 4950, 12};
printf("%s: %d.%02d (%d in stock)\n", p.name, p.price_cents / 100, p.price_cents % 100, p.stock);
p.stock -= 2; // fields are accessed with .
printf("after selling 2: %d left\n", p.stock);
struct product q = {.name = "Mouse", .stock = 40, .price_cents = 1999}; // designated initialisers
printf("%s costs %d cents\n", q.name, q.price_cents);
return 0;
}Keyboard: 49.50 (12 in stock) after selling 2: 10 left Mouse costs 1999 cents
Designated initialisers (.name = …) can be in any order, and any field you leave out is set to zero. They make code much clearer than remembering positions.
typedef: shorter names
Writing struct product everywhere gets tiring. typedef gives the type a one-word name:
#include <stdio.h>
typedef struct {
double x, y;
} Point;
typedef struct {
Point top_left;
Point bottom_right;
} Rect;
double area(Rect r) {
return (r.bottom_right.x - r.top_left.x) * (r.bottom_right.y - r.top_left.y);
}
int main(void) {
Rect r = {.top_left = {0, 0}, .bottom_right = {4, 2.5}};
printf("area = %.1f\n", area(r));
Point copy = r.bottom_right; // structs can be copied with =
copy.x = 100;
printf("copy.x = %.1f, original x is still %.1f\n", copy.x, r.bottom_right.x);
return 0;
}area = 10.0 copy.x = 100.0, original x is still 4.0
Structs can contain other structs. Assigning one struct to another copies every field, and passing a struct to a function copies it too.
Pointers to structs and ->
Copying a large struct into every function call is wasteful, and the function can't change the original. Pass a pointer instead, and use -> to reach the fields:
#include <stdio.h>
typedef struct {
char owner[32];
long balance_cents;
} Account;
int withdraw(Account *acc, long amount) {
if (amount <= 0 || amount > acc->balance_cents) return -1;
acc->balance_cents -= amount; // same as (*acc).balance_cents
return 0;
}
void print_account(const Account *acc) {
printf("%s: %ld.%02ld\n", acc->owner, acc->balance_cents / 100, acc->balance_cents % 100);
}
int main(void) {
Account a = {"Asha", 10000};
print_account(&a);
if (withdraw(&a, 2550) == 0) print_account(&a);
if (withdraw(&a, 99999) != 0) printf("withdrawal refused: not enough money\n");
return 0;
}Asha: 100.00 Asha: 74.50 withdrawal refused: not enough money
p->field is shorthand for (*p).field. Use const Account * for functions that only read, exactly as with other pointers.
Arrays of structs
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *name;
int age;
double score;
} Student;
int by_score_desc(const void *a, const void *b) {
double x = ((const Student *)a)->score, y = ((const Student *)b)->score;
return (x < y) - (x > y);
}
int main(void) {
Student class[] = {
{"Asha", 21, 88.5},
{"Ravi", 22, 92.0},
{"Lee", 20, 79.25},
{"Mira", 21, 92.0},
};
size_t n = sizeof class / sizeof class[0];
qsort(class, n, sizeof class[0], by_score_desc);
for (size_t i = 0; i < n; i++) {
printf("%zu. %-5s %2d %6.2f\n", i + 1, class[i].name, class[i].age, class[i].score);
}
return 0;
}1. Ravi 22 92.00 2. Mira 21 92.00 3. Asha 21 88.50 4. Lee 20 79.25
This is C's version of a list of objects or a table of rows.
Memory layout and padding
The compiler may add invisible padding bytes between fields so each one starts at an address the CPU can read quickly:
#include <stdio.h>
#include <stddef.h>
struct loose { char a; int b; char c; };
struct tight { int b; char a; char c; };
int main(void) {
printf("loose: %zu bytes (b at offset %zu, c at %zu)\n",
sizeof(struct loose), offsetof(struct loose, b), offsetof(struct loose, c));
printf("tight: %zu bytes\n", sizeof(struct tight));
return 0;
}loose: 12 bytes (b at offset 4, c at 8) tight: 8 bytes
Same three fields, but ordering them from biggest to smallest saved 4 bytes. With millions of structs in memory, that matters. It's also why you must never write a struct to a file or network with fwrite and expect another compiler or CPU to read it back the same way: serialise each field explicitly.
Enums
An enum names a set of integer constants:
#include <stdio.h>
typedef enum {
ORDER_PENDING, // 0
ORDER_PAID, // 1
ORDER_SHIPPED, // 2
ORDER_CANCELLED, // 3
} OrderStatus;
const char *status_name(OrderStatus s) {
switch (s) {
case ORDER_PENDING: return "pending";
case ORDER_PAID: return "paid";
case ORDER_SHIPPED: return "shipped";
case ORDER_CANCELLED: return "cancelled";
}
return "unknown";
}
int main(void) {
OrderStatus s = ORDER_PAID;
printf("status %d is \"%s\"\n", s, status_name(s));
s = ORDER_SHIPPED;
printf("now \"%s\"\n", status_name(s));
return 0;
}status 1 is "paid" now "shipped"
Enums make code readable (ORDER_PAID instead of 1), and with -Wall, GCC warns if a switch over an enum forgets a case. Prefix the names (ORDER_…): all enum names share one global namespace.
Unions
A union has several fields that share the same memory: it holds only one of them at a time. Paired with an enum that says which one is active (a tagged union), it represents "one of several kinds of value":
#include <stdio.h>
typedef enum { VAL_INT, VAL_DOUBLE, VAL_TEXT } ValueKind;
typedef struct {
ValueKind kind;
union {
long i;
double d;
const char *s;
} as;
} Value;
void print_value(Value v) {
switch (v.kind) {
case VAL_INT: printf("int %ld\n", v.as.i); break;
case VAL_DOUBLE: printf("double %.3f\n", v.as.d); break;
case VAL_TEXT: printf("text \"%s\"\n", v.as.s); break;
}
}
int main(void) {
Value values[] = {
{VAL_INT, {.i = 42}},
{VAL_DOUBLE, {.d = 3.14159}},
{VAL_TEXT, {.s = "hello"}},
};
for (int i = 0; i < 3; i++) print_value(values[i]);
printf("sizeof(Value) = %zu bytes (the union is as big as its largest field)\n", sizeof(Value));
return 0;
}int 42 double 3.142 text "hello" sizeof(Value) = 16 bytes (the union is as big as its largest field)
This is how interpreters store values of different types (a Python object, a JSON value, a database cell) in one kind of variable.
Bit fields and flags
When you need many on/off settings, store them as bits in one integer:
#include <stdio.h>
enum {
PERM_READ = 1 << 0, // 1
PERM_WRITE = 1 << 1, // 2
PERM_EXEC = 1 << 2, // 4
};
int main(void) {
unsigned perms = PERM_READ | PERM_WRITE; // turn bits on
printf("perms = %u\n", perms);
printf("can write? %s\n", (perms & PERM_WRITE) ? "yes" : "no");
printf("can exec? %s\n", (perms & PERM_EXEC) ? "yes" : "no");
perms |= PERM_EXEC; // add one
perms &= ~PERM_WRITE; // remove one
printf("perms = %u (read + exec)\n", perms);
return 0;
}perms = 3 can write? yes can exec? no perms = 5 (read + exec)
| combines flags, & tests them, ~ flips them. This is exactly how Linux file permissions (0755) and open() flags (O_CREAT | O_WRONLY) work.
Practice
- Define a
Bookstruct (title, author, year, pages) and print an array of three books sorted by year. - Write
void apply_discount(Product *p, int percent)that lowers a product's price in place. - Make an enum for traffic-light colours and a function that returns the next colour.
- Create a tagged union
Shapethat is either a circle (radius) or a rectangle (width, height), and a function that computes its area.
1.Account *a points to a struct. How do you read its balance field?
2.What does struct product q = {.stock = 5}; set the other fields to?
3.Why might sizeof a struct be bigger than the sum of its fields?
4.What's special about a union?