Coding Techniques
Declarations and Initializations · Study material
Designated initializers for lookup tables
Indexing a table by enum constants ties each entry to its value, so reordering or adding enum members cannot silently shift the table.
#include <stdio.h>
enum color { RED, GREEN, BLUE, COLOR_COUNT };
static const char *const names[COLOR_COUNT] = { /* each entry is tied to its enum value */
[BLUE] = "blue",
[RED] = "red",
[GREEN] = "green",
};
int main(void) {
for (int c = 0; c < COLOR_COUNT; c++)
printf("%d=%s ", c, names[c]);
printf("\n");
return 0;
}
0=red 1=green 2=blue
Declare in headers, define in one source file
/* config.h – included everywhere */
extern int max_connections; /* declaration */
int connect_all(int limit); /* prototype */
/* config.c – exactly one definition */
#include "config.h"
int max_connections = 64;
int connect_all(int limit) { /* … */ return limit; }Putting int max_connections = 64; in the header would define it in every file that includes the header – a "multiple definition" link error.
One declarator per line, initialised at once
int *head = NULL; /* clear: one pointer, already valid */
int *tail = NULL;
size_t count = 0;
int* a, b; /* misleading: only a is a pointer */Declaring each variable where it is first used, with a value, prevents both "garbage" bugs and pointer-declarator surprises.
Good declaration habits
- Initialise every variable in its declaration.
- Use designated initializers for structs with more than two members.
- Use
{0}(or C23{}) to zero an aggregate. - Mark read-only data
constand file-private globalsstatic. - Use
volatileonly for hardware registers and signal-handler flags – it is not a threading tool. - Prototype every function; write
(void)for no parameters.