This is without side effects and works for any primitive number:
#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 ? __b : __a; })
#define CLAMP(x, low, high) ({
__typeof__(x) __x = (x);
__typeof__(low) __low = (low);
__typeof__(high) __high = (high);
__x > __high ? __high : (__x < __low ? __low : __x);
})
Can be used like so
int clampedInt = CLAMP(computedValue, 3, 7);
double clampedDouble = CLAMP(computedValue, 0.5, 1.0);
Other suggested names instead of CLAMP
can be VALUE_CONSTRAINED_LOW_HIGH
, BOUNDS
, CLIPPED
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…