CC Explainer
C · 3 · Structs, Unions & I/O12 / 35 · 34%

Structs, Unions & Enums

Compose primitive types into meaningful records.

shortcuts: ← prev · → next · M mark
1

struct

A record with named fields. Access with . (value) or -> (pointer).

Example
example
struct Point { int x, y; };

struct Point p = {3, 4};
printf("%d %d\n", p.x, p.y);

struct Point *pp = &p;
printf("%d\n", pp->y);  // arrow
2

typedef struct

Skip the struct keyword everywhere by naming the type.

Example
example
typedef struct {
    int x, y;
} Point;

Point p = {1, 2};
3

union

All fields share the same memory. sizeof(union) = sizeof(biggest field).

Example
example
union Value {
    int    i;
    float  f;
    char   bytes[4];
};

union Value v;
v.i = 0x40490fdb;
printf("%f\n", v.f); // ~pi (type-punning)
4

enum

Named integer constants. Great with switch.

Example
example
typedef enum { RED, GREEN, BLUE } Color;
Color c = GREEN;   // == 1