如何写一个’clamp’/’clip’/’bound’宏来返回给定范围内的值?

我经常发现自己在写类似的东西

int computedValue = ...; return MAX(0, MIN(5, computedValue)); 

我希望能够将其写为单个单行宏。 它必须没有副作用,就像现有的系统宏MIN和MAX一样,并且应该适用于与MIN和MAX相同的数据类型。

任何人都可以告诉我如何将其变成一个宏吗?

这没有副作用,适用于任何原始数字:

 #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);\ }) 

可以像这样使用

 int clampedInt = CLAMP(computedValue, 3, 7); double clampedDouble = CLAMP(computedValue, 0.5, 1.0); 

其他建议的名称而不是CLAMP可以是VALUE_CONSTRAINED_LOW_HIGHBOUNDSVALUE_CONSTRAINED_LOW_HIGH

摘自本网站http://developer.gnome.org/glib/2.34/glib-Standard-Macros.html#CLAMP:CAPS

 #define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) 

也许你想这样尝试:

 template  const T& clamp(const T& value, const T& low, const T& high) { return value < low ? low: value > high? high: value; } 
  #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MIN(a, b) (((a) > (b)) ? (b) : (a)) 

在一个#define指令中制作它不会非常易读。

仅使用一个比较操作:

 static inline int clamp(int value, int min, int max) { return min + MIN((unsigned int)(value - min), max - min) }