1

When a public function accepts a float value, and this value is to be kept within a specific range, I usually do:

void setParameter(float p)
{
  if (p < 0) p = 0;
  if (p > 1.f) p = 1.f;
  // ...do something with 'p'
}

Is there a better, faster, more elegant way to keep a float value in range?

alk
  • 69,737
  • 10
  • 105
  • 255
Mark Miles
  • 706
  • 8
  • 20
  • 2
    Many libraries offer a function usually named `clamp` that does this. It could be called like `p = clamp(p, 0.0f, 1.0f);` but internally, it will probably do the same. If you need this often, you can write your own `clamp` function. – 5gon12eder Mar 13 '15 at 16:56
  • 1
    I'm partial to `fmax(0, fmin(1.0, p))` although it has different behaviour if p is NaN (more usable with C generics and tgmath.h) – rici Mar 13 '15 at 17:02
  • @rici Is the "different behavior" in that `fmin(1.0, NaN)` --> `1.0` whereas `if (NaN > 1.f)` is false, leaving `p` as NaN? – chux - Reinstate Monica Mar 13 '15 at 17:10

0 Answers0