Coding Techniques
Structures, Unions, Enums · Study material
Sorting an array of structures
Keep records in an array of structs and sort them with qsort(); the comparator casts its const void * arguments back to the struct type.
#include <stdio.h>
#include <stdlib.h>
struct emp {
const char *name;
int salary;
};
static int by_salary_desc(const void *a, const void *b) {
const struct emp *x = a, *y = b;
return (y->salary > x->salary) - (y->salary < x->salary);
}
int main(void) {
struct emp team[] = {{"Asha", 72000}, {"Ravi", 95000}, {"Meera", 61000}, {"John", 88000}};
qsort(team, 4, sizeof team[0], by_salary_desc);
for (int i = 0; i < 4; i++)
printf("%-6s %d\n", team[i].name, team[i].salary);
return 0;
}
Ravi 95000 John 88000 Asha 72000 Meera 61000
Bit-fields for compact flags
Bit-fields pack several small values into one word – handy for flags and hardware registers. The layout is implementation-defined, so do not use them for file or network formats.
#include <stdio.h>
struct perms {
unsigned read : 1; /* one bit each */
unsigned write : 1;
unsigned exec : 1;
};
int main(void) {
struct perms p = {.read = 1, .exec = 1};
printf("r=%u w=%u x=%u, sizeof = %zu\n", p.read, p.write, p.exec, sizeof p);
return 0;
}
r=1 w=0 x=1, sizeof = 4
X-macros: one list for the enum and its names
Write the list once and expand it twice – as enum constants and as strings – so the names can never get out of step with the values.
#include <stdio.h>
#define COLORS(X) X(RED) X(GREEN) X(BLUE) /* the list, written once */
#define AS_ENUM(name) name,
#define AS_TEXT(name) #name,
enum color { COLORS(AS_ENUM) COLOR_COUNT };
static const char *color_name[] = { COLORS(AS_TEXT) };
int main(void) {
for (int c = 0; c < COLOR_COUNT; c++)
printf("%d %s\n", c, color_name[c]);
return 0;
}
0 RED 1 GREEN 2 BLUE
Comparing structures correctly
== does not work on structs, and memcmp() also compares padding bytes, whose values are unspecified. Write a comparison function.
#include <stdbool.h>
#include <string.h>
bool same_student(const struct student *a, const struct student *b) {
return a->roll == b->roll && strcmp(a->name, b->name) == 0;
} Good structure habits
- Initialise with designated initializers:
{.x = 1, .y = 2}. - Order members from largest to smallest alignment to cut padding.
- Pass large structs as
const struct t *. - Write a "deep copy" function when a struct owns heap memory.
- Always store a tag with a union.
- Use
offsetof(), never hand-computed offsets.