Skip to content

Commit 3171589

Browse files
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 52a24bc. * Revert "add a CMake check for __typeof__() availability" This reverts commit 24d14f5.
1 parent fc6d14c commit 3171589

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/doomtype.h

+18-4
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,25 @@ typedef byte lighttable_t;
7474

7575
#define arrlen(array) (sizeof(array) / sizeof(*array))
7676

77-
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
78-
79-
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
77+
#if defined(__GNUC__) || defined(__clang__)
78+
#define MIN(a,b) \
79+
({ \
80+
__typeof__ (a) _a = (a); \
81+
__typeof__ (b) _b = (b); \
82+
_a < _b ? _a : _b; \
83+
})
84+
#define MAX(a,b) \
85+
({ \
86+
__typeof__ (a) _a = (a); \
87+
__typeof__ (b) _b = (b); \
88+
_a > _b ? _a : _b; \
89+
})
90+
#else
91+
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
92+
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
93+
#endif
8094

81-
#define BETWEEN(l, u, x) ((l) > (x) ? (l) : (x) > (u) ? (u) : (x))
95+
#define BETWEEN(l, u, x) (MAX((l), (MIN((u), (x)))))
8296

8397
#define DIV_ROUND_FLOOR(n, d) (((n) - (d) / 2) / (d))
8498

0 commit comments

Comments
 (0)