I get confused over min and max functions, in certain contexts.
In one context, when you're using the functions to take the greater or lesser of two values, there is no issue. For example,
//how many autographed CD's can I give out?
int howManyAutographs(int CDs, int Cases, int Pens)
{
//if no pens, then I cannot sign any autographs
if (Pens == 0)
return 0;
//I cannot give away a CD without a case or a case without a CD
return min(CDs, Cases);
}
Easy. But in another context, I get confused. If I'm trying to set a maximum or minimum, I get it backwards.
//return the sum, with a maximum of 255
int cappedSumWRONG(int x, int y)
{
return max(x + y, 255); //nope, this is wrong
}
//return the sum, with a maximum of 255
int cappedSumCORRECT(int x, int y)
{
return min(x + y, 255); //much better, but counter-intuitive to my mind
}
Is it inadvisable to make my own functions as follows?
//return x, with a maximum of max
int maximize(int x, int max)
{
return min(x, max);
}
//return x, with a minimum of min
int minimize(int x, int min)
{
return max(x, min)
}
Obviously, using the builtins will be faster but this seems like a needless microoptimization to me. Is there any other reason this would be inadvisable? What about in a group project?
std::clamp
function or something similar.up_to
(formin
) andat_least
(formax
)? I think they convey the meaning better thanminimize
, etc. although it may take a moment's thought to realise why they're commutative.min
andmax
and alsominimize
andmaximize
are totally wrong names for the functions you want to write. The defaultmin
andmax
make much more sense. You actually ALMOST got the function names right. This operation is called clamping or capping and you have written two capping functions. I'd suggestcapUpperBound
andcapLowBound
. I don't have to explain to anyone which one does which, it's obvious.