~skeeto/public-inbox

1

Useful macro for C arrays

Julien Vernay <julien@jvernay.fr>
Details
Message ID
<sH6o1LHKbi1f7rrHn6oLB-PsehtcEU5-obxsd2oeRdS36BI-CpO2XmTBKaSlWHJcx66_PMuyprT6Dac1ac7HnLwZLoe_vhS5lMDC9P1Fc5Y=@jvernay.fr>
DKIM signature
pass
Download raw message
Hello Chris,

In addition to your extensive documentation on the arena allocator,
I have found the following macro useful when working in C, which I wanted to share.

    /// Macro to add 'n' elements to a fixed array 'dst' whose logical size
    /// is stored in 'pCount' (in number of elements).
    #define pushN(dst, pCount, n) \
        (*(pCount) < countof(dst) - n \
            ? (*(pCount) += n, dst + (*(pCount) - n)) : NULL)

    /// Macro to add one element to a fixed array 'dst' whose logical size
    /// is stored in 'pCount' (in number of elements).
    #define push(dst, pCount) pushN(dst, pCount, 1)

They allow to use a fixed array as a dynamic array with fixed capacity.
For instance:

    Vertex vertices[300];
    int32_t vertexCount = 0;
    

    for (...) {
        Vertex* pVertex = push(vertices, &vertexCount);
        if (pVertex == NULL)
            break;
        *pVertex = (Vertex){ ... };
    }

Alternatively, you can pass an extra argument for the capacity, so it can
be used in functions receiving (pointer + capacity) as arguments.

Another tool for minimalist libraries and codebases :)

Have a nice day,
- Julien Vernay
Details
Message ID
<20240310212802.x4cc2t2srjdbanlq@nullprogram.com>
In-Reply-To
<sH6o1LHKbi1f7rrHn6oLB-PsehtcEU5-obxsd2oeRdS36BI-CpO2XmTBKaSlWHJcx66_PMuyprT6Dac1ac7HnLwZLoe_vhS5lMDC9P1Fc5Y=@jvernay.fr> (view parent)
DKIM signature
missing
Download raw message
Nice macros, Julien, and in the same spirit as my dynamic array macro. I 
like that even the sizes are type-generic, at least for signed sizes. It 
also illustrates the usefulness of signed sizes: No overflow subtracting 
from the countof result, i.e. n > countof(dst).
Reply to thread Export thread (mbox)