Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

objective c - How can I write a 'clamp' / 'clip' / 'bound' macro for returning a value in a given range?

I often find myself writing something like

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...