Part 0 · 1 chapters · ~8 min

C from Zero

A first program, compiling with clang or gcc, types and their sizes, stdint.h, operators, control flow, functions, structs and padding, arrays, strings as zero-terminated bytes, the preprocessor, header files, and reading compiler warnings.

1

A first program

code
#include <stdio.h>
#include <stdint.h>

typedef struct { int64_t kobo; char currency[4]; } Money;      // "NGN" + zero byte

static void print_money(const Money *m) {                     // pass a pointer, not a copy
    printf("%s %lld.%02lld\n", m->currency, (long long)(m->kobo / 100), (long long)(m->kobo % 100));
}

int main(void) {
    Money m = { .kobo = 420000, .currency = "NGN" };
    print_money(&m);                                          // NGN 4200.00
    printf("sizeof(Money) = %zu\n", sizeof(Money));           // 16: 8 + 4, padded to 8-byte alignment
    return 0;
}
// build: clang -std=c17 -Wall -Wextra -O2 -o money money.c && ./money

Always compile with -Wall -Wextra: most beginner bugs (unused results, wrong printf formats, signed/unsigned comparisons) are warnings first.

C IN SIX IDEAS
the whole language rests on these
types are sizesint, long, char: fixed bytewidths. Use int64_t from stdint.hfor money.no objectsstructs group fields; functionstake pointers to them.arrays decayAn array passed to a functionbecomes a pointer; its length islost.stringsA char array ending in a zerobyte. No length stored anywhere.manual memorymalloc returns bytes; you freethem exactly once.no safety netOut-of-bounds access is undefinedbehaviour, not an exception.
swipe the figure sideways, or tap expand for full screen
1/5
sizes
C types map to machine words. int is usually 4 bytes, long 8 on 64-bit Linux and macOS (4 on Windows). For exact widths use int32_t, int64_t, uint8_t.
types are byte widthsstdint.h for exact sizes