#Macro for typesafe generic arrays in C?

12 messages · Page 1 of 1 (latest)

ivory nova
#

Hi! I'm new to C (about 5 months) and really wanted to have generic typesafe array operations. I found out about macros and tried to implement them in that way. Was there a better way to do this? here is the repo (https://github.com/Yoguti/typesafe-generic-arrays)
but the main part is essentially:

#ifndef GEN_ARR
#define GEN_ARR

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define DEFINE_ARRAY_TYPE(T) \
    typedef struct { \
        T *data; \
        size_t length; \
        size_t capacity; \
    } Array_##T; \
    \
    static void array_init_##T(Array_##T *arr, size_t capacity) { \
        arr->data = (T *)malloc(sizeof(T) * capacity); \
        arr->length = 0; \
        arr->capacity = capacity; \
    } \
    static void array_reverse_##T(Array_##T *arr) { \
        for (int i = 0; i < (int)arr->length / 2; i++) { \
            T temp = arr->data[i]; \
            arr->data[i] = arr->data[arr->length - 1 - i]; \
            arr->data[arr->length - 1 - i] = temp; \
        } \
    } \```
GitHub

Simple library for type safe generic array manipulations in C using macros. - GitHub - Yoguti/typesafe-generic-arrays: Simple library for type safe generic array manipulations in C using macros.

ruby saffronBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

wary pumice
#

Concatenating the type into the name isn’t generally recommended, since it’ll break whenever you use a type with a space or special character in it, e.g long long, int *, or void (*)(int)

ivory nova
#

oh thank you, I didn't even think about that

wary pumice
#

Yep. It’s better to have the user pass the name they want as an argument to the macro and then use that in the names

ruby saffronBOT
#

@ivory nova Has your question been resolved? If so, type !solved :)

ivory nova
#

!solved

ruby saffronBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

ornate sun
#

ideally, allow the user to specify which linkage to use, and whether to use inline

#

though this does require multiple macros to work correctly, one for just the type definitions and function declarations; one for just the function definitions; and one for just the function declarations again to ease use with inline while not using static as well