Re: CLAMP()



Davina Armstrong <davina lickey com> writes:

What does CLAMP() do?  I've grep'd the code, but I can't even figure out
where it's defined.

jrb redhat com wrote:
#define CLAMP(x, low, high)  (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))

CLAMP (5, 0, 10) == 5
CLAMP (-100, 0, 10) == 0
CLAMP (100, 0, 10) == 10

In other words, it uses the first argument as long as it's between the
second and third, otherwise it uses the corersponding high or low value.

You could write, more clearly:

int
NearestValueBetween(
    int value,
    int NoLowerThan,
    int NoGreaterThan
)
{
    if (value < NoLowerThan) return NoLowerThan;
    if (value > NoGreaterThan) return NoGreaterThan;
    return value;
}

Note that CLAMP evaluates its argument more than once, so
    CLAMP(i++, j, k--)
will not behave predictably.

Lee, who is trying to avoid working and had better get down to it!

-- 
Liam Quin - Barefoot in Toronto - liam holoweb net - http://www.holoweb.net/
Ankh: irc.sorcery.net www.valinor.sorcery.net irc.gnome.org www.advogato.org
author, The Open Source XML Database Toolkit, Wiley, August 2000
Co-author, The XML Specification Guide, Wiley, 1999




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]