From 1a07391a97504672588516becc0c02de4702fd11 Mon Sep 17 00:00:00 2001 From: ISSOtm Date: Sun, 31 Oct 2021 07:53:22 +0100 Subject: [PATCH] Introduce `ARRAY_SIZE` macro Checked by `checkpatch`, and you know what? Not a bad thing See https://github.com/gbdev/rgbds/pull/931#discussion_r738856724 --- include/helpers.h | 4 ++++ src/asm/lexer.c | 5 ++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/include/helpers.h b/include/helpers.h index 3dd17884..5284f51a 100644 --- a/include/helpers.h +++ b/include/helpers.h @@ -89,4 +89,8 @@ #define STR(x) #x #define EXPAND_AND_STR(x) STR(x) +// Obtaining the size of an array; `arr` must be an expression, not a type! +// (Having two instances of `arr` is OK because the contents of `sizeof` are not evaluated.) +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof *(arr)) + #endif /* HELPERS_H */ diff --git a/src/asm/lexer.c b/src/asm/lexer.c index 6832ecfc..2c180b59 100644 --- a/src/asm/lexer.c +++ b/src/asm/lexer.c @@ -618,7 +618,7 @@ void lexer_Init(void) */ uint16_t usedNodes = 1; - for (size_t i = 0; i < sizeof(keywords) / sizeof(*keywords); i++) { + for (size_t i = 0; i < ARRAY_SIZE(keywords); i++) { uint16_t nodeID = 0; /* Walk the dictionary, creating intermediate nodes for the keyword */ @@ -645,8 +645,7 @@ void lexer_Init(void) #ifdef PRINT_NODE_COUNT /* For the maintainer to check how many nodes are needed */ printf("Lexer keyword dictionary: %zu keywords in %u nodes (pool size %zu)\n", - sizeof(keywords) / sizeof(*keywords), usedNodes, - sizeof(keywordDict) / sizeof(*keywordDict)); + ARRAY_SIZE(keywords), usedNodes, ARRAY_SIZE(keywordDict)); #endif }