typestar

The array length macro in C

One macro every C project has, and the one place it must not be used.

#include <stddef.h>

#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))

int sum_all(void) {
    int values[] = {2, 4, 6, 8, 10};
    int total = 0;
    for (size_t i = 0; i < ARRAY_LEN(values); i++) {
        total += values[i];
    }
    return total;
}

size_t count_names(void) {
    const char *names[] = {"ada", "grace", "alan"};
    return ARRAY_LEN(names);
}

How it works

  1. Dividing the array size by an element size gives the count.
  2. It only works where the array type is visible.
  3. On a pointer it silently computes nonsense.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
329
Tokens
101
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 3 of 4 in Macros, step 3 of 12 in Preprocessor & headers.

← Previous Next →