0

Is there a more concise way to write the following code?

if (myValue > 100) 
  myValue = 100;
if (myValue < 0) 
  myValue = 0;

Thanks in advance for your wisdom!

BeachRunnerFred
  • 18,070
  • 35
  • 139
  • 238

2 Answers2

4

You can use MAX and MIN, though it's not necessarily as clear.

myValue = MAX(MIN(myValue, 100), 0);
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0
myValue = (myValue > 100) ? 100 : myValue;
myValue = (myValue < 0) ? 0 : myValue;

or

myValue = (myValue > 100) ? 100 : ((myValue < 0) ? 0 : myValue);

of course I would use MIN/MAX even if you do 2 lines.

maybe even

#define MINMAX(_min_,_max_,_n_) (MAX(MIN(_n_, _max_), _min_))
Grady Player
  • 14,399
  • 2
  • 48
  • 76