From 31715892fe86631000983cc90e6179579c3b8e9b Mon Sep 17 00:00:00 2001 From: Fabian Greffrath Date: Wed, 1 Jan 2025 17:43:06 +0100 Subject: [PATCH] add type-safe MIN() and MAX() macros (#2112) * add type-safe MIN() and MAX() macros https://stackoverflow.com/questions/3437404/min-and-max-in-c * add a CMake check for __typeof__() availability * extend CMake check for statement expressions * Revert "extend CMake check for statement expressions" This reverts commit 52a24bcadcfc42746ba5f39ddb42d317248f9b4c. * Revert "add a CMake check for __typeof__() availability" This reverts commit 24d14f592af7b9615666a5f86ecee90c552dd70d. --- src/doomtype.h | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/doomtype.h b/src/doomtype.h index 2c7f587f0..eebd266f6 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -74,11 +74,25 @@ typedef byte lighttable_t; #define arrlen(array) (sizeof(array) / sizeof(*array)) -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) - -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#if defined(__GNUC__) || defined(__clang__) + #define MIN(a,b) \ + ({ \ + __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a < _b ? _a : _b; \ + }) + #define MAX(a,b) \ + ({ \ + __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a > _b ? _a : _b; \ + }) +#else + #define MIN(a, b) (((a) < (b)) ? (a) : (b)) + #define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif -#define BETWEEN(l, u, x) ((l) > (x) ? (l) : (x) > (u) ? (u) : (x)) +#define BETWEEN(l, u, x) (MAX((l), (MIN((u), (x))))) #define DIV_ROUND_FLOOR(n, d) (((n) - (d) / 2) / (d))