Anton Dolganin

I'm an engineer focused on solving problems, not tied to any specific language. Architecture, development, DevOps โ€” I choose the right tools for the job and build solutions that work in production and scale without pain.

๐Ÿ“Œ 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: ")
};

After preprocessing it becomes:


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

โ€” 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;
}

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

String + Length: A Zero-Overhead Trick in C