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

hfo*_*sli 9 c macros objective-c predefined-macro

我经常发现自己写的东西

int computedValue = ...;
return MAX(0, MIN(5, computedValue));
Run Code Online (Sandbox Code Playgroud)

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

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

hfo*_*sli 18

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

#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);\
  })
Run Code Online (Sandbox Code Playgroud)

可以像这样使用

int clampedInt = CLAMP(computedValue, 3, 7);
double clampedDouble = CLAMP(computedValue, 0.5, 1.0);
Run Code Online (Sandbox Code Playgroud)

其他建议的名称,而不是CLAMP可以VALUE_CONSTRAINED_LOW_HIGH,BOUNDS,CLIPPED.