DEV Community

Cover image for String + Length: A Zero-Overhead Trick in C
Anton Dolganin
Anton Dolganin

Posted on

String + Length: A Zero-Overhead Trick in C

#c

πŸ“Œ Problem

In C you often need to keep a string together with its length. Calling strlen() every time means extra memory scans. We want it compact and efficient.

βœ… Solution

A tiny trick with typedef + macro:


typedef struct { const char *p; size_t n; } sv;
#define SV(s) { (s), sizeof(s) - 1 }

struct Messages {
    sv error, version, rep_prefix;
};

static const struct Messages mess = {
    SV("error"),
    SV("version"),
    SV("Server reply: ")
};
Enter fullscreen mode Exit fullscreen mode

After preprocessing it becomes:


static const struct Messages mess = {
    { ("error"),          sizeof("error") - 1 },
    { ("version"),        sizeof("version") - 1 },
    { ("Server reply: "), sizeof("Server reply: ") - 1 }
};
Enter fullscreen mode Exit fullscreen mode

β€” string and its length, no redundant strlen().

Usage


#include <stdio.h>

int main(void) {
    fwrite(mess.rep_prefix.p, 1, mess.rep_prefix.n, stdout);
    fwrite("OK\n", 1, 3, stdout);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Handy in network protocols, logging, binary formats β€” string + size always at hand, zero overhead.

Top comments (0)