如何编写“clamp"/“clip"/“bound"宏来返回给定范围内的值? [英] How can I write a 'clamp' / 'clip' / 'bound' macro for returning a value in a given range?

查看:18
本文介绍了如何编写“clamp"/“clip"/“bound"宏来返回给定范围内的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I often find myself writing something like

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

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

I would like to be able to write this as a single one-line macro. It must be free of side effects, in the same way that the existing system macros MIN and MAX are, and should work for the same data types as MIN and MAX.

谁能告诉我如何把它变成一个宏?

Can anyone show me how to turn this into a single macro?

推荐答案

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

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

可以这样使用

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

代替 CLAMP 的其他建议名称可以是 VALUE_CONSTRAINED_LOW_HIGHBOUNDSCLIPPED.

Other suggested names instead of CLAMP can be VALUE_CONSTRAINED_LOW_HIGH, BOUNDS, CLIPPED.

这篇关于如何编写“clamp"/“clip"/“bound"宏来返回给定范围内的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆