🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →String Lookup Tables in C
Turn a number into readable text with an array of pointers to strings. Learn enum-indexed tables, bounds checking and flash-friendly const tables in this free embedded C programming lecture.
A string lookup table in C maps a small integer, such as an error code or a month number, to a message. It replaces long switch statements with one array and one index. Firmware engineers use this pattern daily in embedded C programming for UART logs, error reports and menu labels. This lecture of our free C programming course shows how to build one the safe, modern way.
What You Will Learn
- How an array of pointers to strings becomes a lookup table
- How to index the table with an enum so code and text never drift apart
- How to protect against out-of-range indexes
- How to keep the table in flash with
static const char *const - Why a table is shorter and faster than a switch
Prerequisites
You need the pointer array lectures (cp9_24 and cp9_25), enums from the Elements of C chapter, and the idea of array indexing.
The Idea: Index Selects the Text
If entry number 2 of the table holds the text for error code 2, then finding the message is a single array access: table[code]. The CPU does one address calculation, with no comparisons and no branches.
Complete Program: Link Error Names
Save as err_table.c:
#include <stdio.h>
enum link_err { ERR_OK, ERR_TIMEOUT, ERR_CRC, ERR_BUSY, ERR_NODEV, ERR_COUNT };
static const char *const err_text[ERR_COUNT] = {
[ERR_OK] = "OK",
[ERR_TIMEOUT] = "TIMEOUT",
[ERR_CRC] = "CRC MISMATCH",
[ERR_BUSY] = "BUSY",
[ERR_NODEV] = "NO DEVICE",
};
static const char *err_to_text(unsigned code)
{
return (code < ERR_COUNT) ? err_text[code] : "UNKNOWN";
}
int main(void)
{
unsigned samples[] = { 0, 2, 4, 9 };
for (size_t i = 0; i < sizeof samples / sizeof samples[0]; i++)
printf("code %u -> %s\n", samples[i], err_to_text(samples[i]));
printf("table entries: %zu\n", sizeof err_text / sizeof err_text[0]);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o err_table err_table.c
./err_table
Expected output:
code 0 -> OK
code 2 -> CRC MISMATCH
code 4 -> NO DEVICE
code 9 -> UNKNOWN
table entries: 5
What each part does
| Piece | Why it is there |
|---|---|
ERR_COUNT as the last enum value | Automatically equals the number of codes, so the array size follows the enum |
[ERR_CRC] = "..." designated initialisers | The text is tied to its code by name, so reordering the enum cannot silently break the table |
static const char *const | The text is const, the pointers are const, so the whole table may live in flash |
code < ERR_COUNT | Bounds check, protects against reading beyond the table |
unsigned parameter | A negative value turns into a huge number, so one comparison rejects both too-large and negative inputs |
Reading the Declaration Right to Left
static const char *const err_text[ERR_COUNT] reads: err_text is an array of const pointers to const char. The first const protects the characters. The second const, placed after the star, protects the pointers. Together they let the linker place the table in read-only memory, which on a microcontroller means flash and zero RAM.
Lookup Table vs switch Statement
| Point | Lookup table | switch |
|---|---|---|
| Code size | One loop or one line | One case per value |
| Adding an entry | Add one line | Add case and return |
| Speed | Constant, single load | Compiler dependent |
| Sparse codes (10, 200, 4000) | Wastes slots | Better fit |
| Reuse in loops | Easy to print all entries | Not possible |
The older approach of reading a date and printing the month name through an array of month names is the same idea. Replace the error codes with the numbers 1 to 12 (subtract one from the index, since arrays start at zero) and you have a month converter. Try it as an exercise.
Real-World Embedded C Use Cases
- Printing state machine names over the debug UART
- Converting HTTP or modem status codes to text on gateways
- Naming GPIO ports or interrupt sources in a diagnostic shell
- Showing day and month names on an LCD or e-paper display
Common Mistakes
No bounds check. Reading err_text[9] reads memory past the table and prints garbage or crashes. Always check against the count.
Off by one. A month table indexed with months[m] instead of months[m - 1] shows the wrong name and overflows for December.
Enum and table out of sync. Adding an enum value without a text entry leaves a NULL slot. Printing NULL with %s is undefined behaviour. Designated initialisers plus a test loop catch this early.
Defensive version
If a slot might be NULL, make the accessor safe:
static const char *err_to_text(unsigned code)
{
if (code >= ERR_COUNT || err_text[code] == NULL)
return "UNKNOWN";
return err_text[code];
}
Memory Cost of the Table
For the five-entry error table, a 32-bit microcontroller stores 5 pointers of 4 bytes each, which is 20 bytes, plus the text itself: 3 + 8 + 13 + 5 + 10 bytes including terminators, so 39 bytes. The whole table is under 60 bytes of flash and no RAM at all when declared static const char *const. Compare this with a switch that returns a literal in every branch: the compiler still stores the same text, but also generates compare and jump instructions for each case.
Best Practices
- End every enum with a count member
- Use designated initialisers for the table
- Wrap the lookup in a small function that does the bounds check
- Keep the table
static constso it stays out of RAM - Print the table in a unit test to catch NULL slots
Performance and Security Notes
The lookup is a single indexed load, so it suits interrupt handlers and tight loops. For security, never use an index that came from the network or a file without checking it first. An unchecked index is a read primitive that attackers can abuse.
Try It Yourself: Weekday and Month Tables
- Weekday name. Build
static const char *const day_name[7]starting with Sunday, and writeday_to_text(unsigned d)with a bounds check that returns “INVALID” for 7 or more. - Month converter. Read a date in the form day/month/year with
scanf, check that the month is between 1 and 12, and printmonth_name[m - 1]. Test it with 0 and 13 to prove your bounds check works. - Self-check loop. Write a loop that walks every slot of
err_textand prints a warning if any entry is NULL. Run it every time you add an enum value, and it will catch a forgotten text line immediately. - Reverse lookup. Write a function that takes a text such as “BUSY” and returns its enum value by comparing against each slot with
strcmp. ReturningERR_COUNTfor not found is a clean way to signal failure.
The reverse lookup is how a serial console turns a typed word back into a command number, so it is worth getting comfortable with both directions of the table.
Summary and Key Takeaways
- An array of pointers to strings is a natural lookup table
- Index with an enum and finish the enum with a count
- Always bounds check before reading the table
- Use
static const char *constto save RAM
Next, we sort a table of strings by swapping pointers instead of characters.
Frequently Asked Questions
What is a string lookup table in C?
An array of pointers to strings where the array index is a number, such as an error code, that selects the matching text.
Why add a count value at the end of an enum?
It automatically equals the number of real values, so it sizes the table and works as the bounds limit.
What does static const char *const mean?
The characters and the pointers are both read-only, and the name is private to the file.
Is a table faster than a switch?
For dense codes starting at zero, usually yes, because it needs one indexed load and no comparisons.
How do I stop an out-of-range code from crashing?
Compare the index with the table size before using it and return a default text otherwise.
Free C Tutorial for Embedded Systems
Up next in our free C programming course: sorting strings by swapping pointers.

2 Comments