IntermediateLesson 10 of 18
structs, typedef, enum & union – C
Building your own data types: structures, enumerations, variants and access via pointers.
A struct bundles several values (even of different types) into a new type. With typedef you give it a short name. You access fields with ., and through a pointer with -> (p->x is (*p).x).
#include <stdio.h>
#include <string.h>
typedef struct {
char name[30];
int alter;
double gehalt;
} Mitarbeiter;
void ausgeben(const Mitarbeiter *m) {
printf("%s, %d years, %.2f EUR\n", m->name, m->alter, m->gehalt);
}
int main(void) {
Mitarbeiter a = {"Ada", 36, 5200.0};
Mitarbeiter b = {.name = "Linus", .alter = 28, .gehalt = 4100.5}; // named
Mitarbeiter c = a; // structs are copied on assignment
strcpy(c.name, "Grace"); // change the copy, the original stays
ausgeben(&a);
ausgeben(&b);
ausgeben(&c);
return 0;
}Structs are copied by value (also on function calls). You therefore pass large structs as const Struct *. An enum gives names to integer constants – ideal for states and options:
#include <stdio.h>
enum Wochentag { MO, DI, MI, DO, FR, SA, SO }; // MO=0, DI=1, ...
typedef enum { ROT = 1, GRUEN = 2, BLAU = 4 } Farbe;
const char *tagname(enum Wochentag t) {
static const char *namen[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
return namen[t];
}
int main(void) {
enum Wochentag heute = MI;
printf("%s %d\n", tagname(heute), heute + 1); // Wed 3
Farbe f = GRUEN;
printf("%d\n", f == GRUEN); // 1
return 0;
}A union places all fields at the same memory location; only one is valid at a time. Together with an enum as a "tag", you get a tagged union (variant type):
#include <stdio.h>
typedef struct {
enum { T_INT, T_DOUBLE } typ;
union { int i; double d; } wert;
} Wert;
void zeige(Wert w) {
if (w.typ == T_INT) printf("int: %d\n", w.wert.i);
else printf("double: %.2f\n", w.wert.d);
}
int main(void) {
Wert a = {T_INT, {.i = 42}};
Wert b = {T_DOUBLE, {.d = 3.14}};
zeige(a);
zeige(b);
return 0;
}TipAlways initialize structs completely, e.g. with
Mitarbeiter m = {0}; – that way all fields are defined as 0. Fields not mentioned in an initializer list are zeroed automatically.WarningThe same applies to strings in structs as everywhere else:
m.name = "Ada"; does not work for a char name[30] (arrays are not assignable). Use strcpy/snprintf.