我怎么能写一个'夹'/'夹'/'约束'宏在给定范围内返回一个值? [英] How can I write a 'clamp' / 'clip' / 'bound' macro for returning a value in a given range?

查看:158
本文介绍了我怎么能写一个'夹'/'夹'/'约束'宏在给定范围内返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己写的东西像

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_HIGH CLIPPED

这篇关于我怎么能写一个'夹'/'夹'/'约束'宏在给定范围内返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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