From c762664ef5990c6e8684d5d8a34f811b18df0465 Mon Sep 17 00:00:00 2001 From: WormHeamer Date: Sat, 8 Feb 2025 02:07:00 -0500 Subject: wrap multi-line macros in do/while(0) loop turn out just a compound statement { ... } block is insufficient, because it can break if/else statements. do { ... } while(0) turns it into just a normal statement. --- dynarr.h | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'dynarr.h') diff --git a/dynarr.h b/dynarr.h index 986c6ab..f8e5f20 100644 --- a/dynarr.h +++ b/dynarr.h @@ -14,35 +14,36 @@ typedef struct { size_t count, capacity; } DynArrHeader; #define DA_HEADER(da) ((DynArrHeader*)(da) - 1) #define DA_INIT_CAP 16 -#define DA_INIT(da) {\ +#define DA_INIT(da) do {\ char *da_init_ptr = ((char*)malloc(sizeof(DynArrHeader) + DA_INIT_CAP * sizeof(*da)));\ if (!da_init_ptr) err(1, "dynamic array allocation failed");\ da = (void *)(da_init_ptr + sizeof(DynArrHeader));\ *DA_HEADER(da) = (DynArrHeader) { 0, DA_INIT_CAP };\ -} +} while(0) #define DA_FREE(da)\ free(DA_HEADER(da)) #define DA_LEN(da) (DA_HEADER(da)->count) -#define DA_FIT(da, count)\ +#define DA_FIT(da, count) do {\ if (count >= DA_HEADER(da)->capacity) {\ while (count >= DA_HEADER(da)->capacity) DA_HEADER(da)->capacity <<= 1;\ char *da_fit_ptr = realloc(DA_HEADER(da), sizeof(DynArrHeader) + DA_HEADER(da)->capacity * sizeof(*da));\ if (!da_fit_ptr) err(1, "dynamic array reallocation failed");\ (da) = (void *)(da_fit_ptr + sizeof(DynArrHeader));\ - } + }\ +} while(0) -#define DA_PUSH(da, ...) {\ +#define DA_PUSH(da, ...) do {\ DA_FIT(da, DA_LEN(da) + 1);\ (da)[DA_HEADER(da)->count++] = (__VA_ARGS__);\ -} +} while(0) -#define DA_PUSH_MULT(da, buf, n) {\ +#define DA_PUSH_MULT(da, buf, n) do {\ DA_FIT(da, DA_LEN(da) + n);\ memcpy(&(da)[DA_HEADER(da)->count], buf, n * sizeof(*(da)));\ DA_HEADER(da)->count += n;\ -} +} while(0) #define DA_FOR(da, name)\ for (typeof(da) name = (da); name < &(da)[DA_LEN(da)]; name++) -- cgit 1.4.1-2-gfad0